SpringBoot2.x整合Mybatis3.x注解
1、使用starter, maven仓库地址:http://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter
2、加入依赖(可以用 http://start.spring.io/ 下载)
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
runtime
mysql
mysql-connector-java
runtime
com.alibaba
druid
1.1.6
加入配置文件
#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
加载配置,注入到sqlSessionFactory等都是springBoot帮我们完成
4、启动类增加mapper扫描
@MapperScan(“net.xdclass.base_project.mapper”)
技巧:保存对象,获取数据库自增id
@Options(useGeneratedKeys=true, keyProperty=“id”, keyColumn=“id”)
4、开发mapper
参考语法 http://www.mybatis.org/mybatis-3/zh/java-api.html
5、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;
本案例的pom.xml文件
org.springframework.boot
spring-boot-starter-parent
2.0.1.RELEASE
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-devtools
true
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
runtime
mysql
mysql-connector-java
runtime
com.alibaba
druid
1.1.6
org.springframework.boot
spring-boot-maven-plugin
application.properties
#可以自动识别
#spring.datasource.driver-class-name =com.mysql.jdbc.Driver
#ken_database数据库名字
spring.datasource.url=jdbc:mysql://localhost:3306/ken_database?useUnicode=true&characterEncoding=utf-8
spring.datasource.username =root
spring.datasource.password =123456
#spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
UserMapper 用于访问数据库的接口,编写SQL语句
package net.xdclass.base_project.mapper;
import net.xdclass.base_project.domain.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Options;
/**
* 功能描述:访问数据库的接口
*/
public interface UserMapper {
//推荐使用#{}取值,不要用${},因为存在注入的风险
@Insert("INSERT INTO user(name,phone,create_time,age) VALUES(#{name}, #{phone}, #{createTime},#{age})")
@Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id") //keyProperty java对象的属性;keyColumn表示数据库的字段
int insert(User user);
//
// @Select("SELECT * FROM user")
// @Results({
// @Result(column = "create_time",property = "createTime") //javaType = java.util.Date.class
// })
// List getAll();
//
//
//
// @Select("SELECT * FROM user WHERE id = #{id}")
// @Results({
// @Result(column = "create_time",property = "createTime")
// })
// User findById(Long id);
//
//
//
// @Update("UPDATE user SET name=#{name} WHERE id =#{id}")
// void update(User user);
//
// @Delete("DELETE FROM user WHERE id =#{userId}")
// void delete(Long userId);
//
}
User类
package net.xdclass.base_project.domain;
import java.util.Date;
public class User {
private int id;
private String name;
private String phone;
private int age;
private Date createTime;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
UserService接口
package net.xdclass.base_project.service;
import net.xdclass.base_project.domain.User;
public interface UserService {
public int add(User user);
//public int addAccount();
}
package net.xdclass.base_project.service.impl;
import java.util.Date;
import net.xdclass.base_project.domain.User;
import net.xdclass.base_project.mapper.UserMapper;
import net.xdclass.base_project.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Override
public int add(User user) {
userMapper.insert(user);
int id = user.getId();
return id;
}
}
UserContorller
package net.xdclass.base_project.controller;
import java.util.Date;
import net.xdclass.base_project.domain.JsonData;
import net.xdclass.base_project.domain.User;
import net.xdclass.base_project.service.UserService;
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;
@RestController
@RequestMapping("/api/v1/user")
public class UserController {
@Autowired
private UserService userService;
/**
* 功能描述: user 保存接口
* @return
*/
@GetMapping("add")
public Object add(){
User user = new User();
user.setAge(11);
user.setCreateTime(new Date());
user.setName("xdclass");
user.setPhone("10010000");
int id = userService.add(user);
return JsonData.buildSuccess(id);
}
// @Autowired
// private UserMapper userMapper;
//
//
//
// @GetMapping("findAll")
// public Object findAll(){
//
// return JsonData.buildSuccess(userMapper.getAll());
// }
//
//
//
// @GetMapping("findById")
// public Object findById(long id){
// return JsonData.buildSuccess(userMapper.findById(id));
// }
//
//
// @GetMapping("del_by_id")
// public Object delById(long id){
// userMapper.delete(id);
// return JsonData.buildSuccess();
// }
//
// @GetMapping("update")
// public Object update(String name,int id){
// User user = new User();
// user.setName(name);
// user.setId(id);
// userMapper.update(user);
// return JsonData.buildSuccess();
// }
//
// //测试事务
// @GetMapping("transac")
// public Object transac(){
// int id = userService.addAccount();
// return JsonData.buildSuccess(id);
// }
//
//
}
package net.xdclass.base_project.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 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
+ "]";
}
}
JsonUtils
package net.xdclass.base_project.utils;
import java.io.IOException;
import org.springframework.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonUtils {
private static ObjectMapper objectMapper = new ObjectMapper();
//对象转字符串
public static String obj2String(T obj){
if (obj == null){
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
//字符串转对象
public static T string2Obj(String str,Class clazz){
if (StringUtils.isEmpty(str) || clazz == null){
return null;
}
try {
return clazz.equals(String.class)? (T) str :objectMapper.readValue(str,clazz);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
启动类
package net.xdclass.base_project;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("net.xdclass.base_project.mapper")
public class XdclassApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(XdclassApplication.class, args);
}
}
项目结构
相关资料:
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#Configuration
https://github.com/mybatis/spring-boot-starter/tree/master/mybatis-spring-boot-samples
整合问题集合:
https://my.oschina.net/hxflar1314520/blog/1800035
https://blog.csdn.net/tingxuetage/article/details/80179772