一、pom.xml中添加相关依赖
<!-- 引入starter-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
<scope>runtime</scope>
</dependency> <!-- MySQL的JDBC驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 引入第三方数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
二、在application.properties中添加Mybatis的配置
#mybatis.type-aliases-package=net.xdclass.base_project.domain
#可以自动识别
#spring.datasource.driver-class-name =com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/movie?useUnicode=true&characterEncoding=utf-8
spring.datasource.username =root
spring.datasource.password =password
#如果不使用默认的数据源 (com.zaxxer.hikari.HikariDataSource)
spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
三、启动文件中加入注解,以便可以自动扫描包里面所有的Mapper文件
四、本地mysql数据库中创建movie库,创建对应的表
//创建表的SQL如下
CREATE TABLE `user` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(128) DEFAULT NULL COMMENT '名称',
`phone` varchar(16) DEFAULT NULL COMMENT '用户手机号',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`age` int(4) DEFAULT NULL COMMENT '年龄',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8;
五、创建一个domain类
package net.Eleven.demo.domain; import java.util.Date; public class UserNew {
private int id;
private String name;
private String phone;
private int age;
private Date creatTime; public int getId() {
return id;
} public String getName() {
return name;
} public String getPhone() {
return phone;
} public int getAge() {
return age;
} public Date getCreatTime() {
return creatTime;
} public void setId(int id) {
this.id = id;
} public void setName(String name) {
this.name = name;
} public void setPhone(String phone) {
this.phone = phone;
} public void setAge(int age) {
this.age = age;
} public void setCreatTime(Date creatTime) {
this.creatTime = creatTime;
} }
六、创建Mapper,访问数据库的接口
package net.Eleven.demo.Mapper; import net.Eleven.demo.domain.UserNew;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options; /**
* 功能描述:访问数据库的接口,相当于dao层
* @author Eleven
*/ public interface UserMapper { //推荐使用#{}取值,不要用${},因为存在注入的风险
@Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name},#{phone},#{creatTime},#{age})") //VALUESDE 的值必须与domain中的字段一一对应。
@Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id") //keyProperty java对象的属性;keyColumn表示数据库的字段
int insert(UserNew userNew);
}
七、创建Service 和Impl
package net.Eleven.demo.Service; import net.Eleven.demo.domain.UserNew; public interface UserService {
public int add(UserNew userNew);
}
package net.Eleven.demo.Service.impl; import net.Eleven.demo.Mapper.UserMapper;
import net.Eleven.demo.Service.UserService;
import net.Eleven.demo.domain.UserNew;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; @Service //不要忘了注解
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper; @Override
public int add(UserNew userNew) {
userMapper.insert(userNew);
int id = userNew.getId();
return id; }
}
八、创建Controller
package net.Eleven.demo.controller; import net.Eleven.demo.Service.UserService;
import net.Eleven.demo.domain.JsonData;
import net.Eleven.demo.domain.UserNew;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import java.util.Date; @RestController
@RequestMapping("/api/sql/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("add")
public Object add(){
UserNew userNew = new UserNew();
userNew.setAge(11);
userNew.setCreatTime(new Date());
userNew.setName("Eleven");
userNew.setPhone("18211111111");
int id = userService.add(userNew);
return JsonData.buildSuccess(id);
} }
九、创建第八步使用的JsonData类,以便更好的展示返回的数据
package net.Eleven.demo.domain; import java.io.Serializable; public class JsonData implements Serializable { /**
*
*/
private static final long serialVersionUID = 1L; private Integer code; // 状态码 0 表示成功,1表示处理中,-1表示失败
private Object data; // 数据
private String msg;// 描述 public JsonData() {
} public JsonData(Integer code, Object data, String msg) {
this.code = code;
this.data = data;
this.msg = msg;
}
public JsonData(int code, Object data) {
super();
this.code = code;
this.data = data;
} // 成功,传入数据
public static JsonData buildSuccess() {
return new JsonData(0, null, null);
} // 成功,传入数据
public static JsonData buildSuccess(Object data) {
return new JsonData(0, data, null);
} // 失败,传入描述信息
public static JsonData buildError(String msg) {
return new JsonData(-1, null, msg);
} // 失败,传入描述信息,状态码
public static JsonData buildError(String msg, Integer code) {
return new JsonData(code, null, msg);
} // 成功,传入数据,及描述信息
public static JsonData buildSuccess(Object data, String msg) {
return new JsonData(0, data, msg);
} // 成功,传入数据,及状态码
public static JsonData buildSuccess(Object data, int code) {
return new JsonData(code, data, null);
} public Integer getCode() {
return code;
} public void setCode(Integer code) {
this.code = code;
} public Object getData() {
return data;
} public void setData(Object data) {
this.data = data;
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
} @Override
public String toString() {
return "JsonData [code=" + code + ", data=" + data + ", msg=" + msg
+ "]";
} }
十、执行结果
十一、遇到的报错
错误提示:
Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: The server time zone value '�й���ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more specifc time zone value if you want to utilize time zone support.
解决办法;
在连接字符串后面加上?serverTimezone=UTC
其中UTC是统一标准世界时间。
完整的连接字符串示例:jdbc:mysql://localhost:3306/test?serverTimezone=UTC
或者还有另一种选择:jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8,这个是解决中文乱码输入问题,当然也可以和上面的一起结合:jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC