加入依賴
< dependency>
< groupId> org.mybatis.spring.boot</ groupId>
< artifactId> mybatis-spring-boot-starter</ artifactId>
< version> 2.1.1</ version>
</ dependency>
配置數據源信息
#集成mysql數據庫的配置
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/community?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
編寫數據庫的實體類com.july.community.model.User
屬性與數據庫的字段對齊
public class User {
private Integer id;
private String name;
private String accountId;
private String token;
private Long timeCreate;
private Long timeModified;
public User ( String name, String accountId, String token, Long timeCreate, Long timeModified) {
this . name = name;
this . accountId = accountId;
this . token = token;
this . timeCreate = timeCreate;
this . timeModified = timeModified;
}
public Integer getId ( ) {
return id;
}
public void setId ( Integer id) {
this . id = id;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public String getAccountId ( ) {
return accountId;
}
public void setAccountId ( String accountId) {
this . accountId = accountId;
}
public String getToken ( ) {
return token;
}
public void setToken ( String token) {
this . token = token;
}
public Long getTimeCreate ( ) {
return timeCreate;
}
public void setTimeCreate ( Long timeCreate) {
this . timeCreate = timeCreate;
}
public Long getTimeModified ( ) {
return timeModified;
}
public void setTimeModified ( Long timeModified) {
this . timeModified = timeModified;
}
}
寫Mapper
com.july.community.mapper.
package com. july. community. mapper;
import com. july. community. model. User;
import org. apache. ibatis. annotations. Insert;
import org. apache. ibatis. annotations. Mapper;
@Mapper
public interface UserMapper {
@Insert ( "insert into tbl_user (name,account_id,token,time_create,time_modified) values (#{name},#{accountId},#{token},#{timeCreate},#{timeModified})" )
void insert ( User user) ;
}
編寫controller中的代碼
User user = new User ( githubUser. getName ( ) , String. valueOf ( githubUser. getId ( ) ) , UUID. randomUUID ( ) . toString ( ) , System. currentTimeMillis ( ) , System. currentTimeMillis ( ) ) ;
userMapper. insert ( user) ;
運行測試
查看數據庫,成功!