spring boot 2整合mybatis
mybatis-spring-boot-starter主要有两种解决方案,一种是使用注解,一种是使用XML。
参考这篇文章动手跑了一个例子,稍微不同之处,原文是spring boot,这里改成了spring boot 2,mybatis现在最新版本为1.3.2。
一、使用注解
1、添加相关maven文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
mybatis-spring-boot-starter最新版本可在官网查询
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html
2、application.properties 添加相关配置
mybatis.type-aliases-package = com.example.demo.entity spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password =
3、实体类User.java
package com.example.demo.entity; import com.example.demo.enums.UserSexEnum; public class User {
public User() {
super();
} public User(String name, UserSexEnum sex) {
super();
this.name = name;
this.sex = sex;
} private Integer id; private String name; private UserSexEnum sex; 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 == null ? null : name.trim();
} public UserSexEnum getSex() {
return sex;
} public void setSex(UserSexEnum sex) {
this.sex = sex;
} @Override
public String toString() {
return "name " + this.name + ", sex " + this.sex;
}
}
4、枚举UserSexEnum.java
package com.example.demo.enums; public enum UserSexEnum {
MAN,
WOMAN
}
5、启动类中添加对mapper包扫描@MapperScan,这样就不需要在每个Mapper类上面添加注解@Mapper。
package com.example.demo; import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication extends SpringBootServletInitializer { public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
6、开发Mapper
package com.example.demo.mapper; import java.util.List; import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update; import com.example.demo.entity.User;
import com.example.demo.enums.UserSexEnum; public interface UserMapper {
@Select("SELECT * FROM user")
//结果集,关联实体类属性和数据库字段一一对应,如果两边一致,就不需要这个属性来修饰。
@Results({
@Result(property = "sex", column = "sex", javaType = UserSexEnum.class),
})
List<User> getAll(); @Select("SELECT * FROM user WHERE id = #{id}")
@Results({
@Result(property = "sex", column = "sex", javaType = UserSexEnum.class),
})
User getOne(Long id); @Insert("INSERT INTO user(name,sex) VALUES(#{name}, #{sex})")
void insert(User user); @Update("UPDATE user SET name=#{name} WHERE id =#{id}")
void update(User user); @Delete("DELETE FROM user WHERE id =#{id}")
void delete(Long id);
}
7、单元测试
package com.example.demo.mapper; import java.util.List; import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; import com.example.demo.entity.User;
import com.example.demo.enums.UserSexEnum; @RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest { @Autowired
private UserMapper UserMapper; @Test
public void testInsert() throws Exception {
UserMapper.insert(new User("aa", UserSexEnum.MAN));
UserMapper.insert(new User("bb", UserSexEnum.WOMAN));
UserMapper.insert(new User("cc", UserSexEnum.WOMAN)); Assert.assertEquals(3, UserMapper.getAll().size());
} @Test
public void testQuery() throws Exception {
List<User> users = UserMapper.getAll();
if(users==null || users.size()==0){
System.out.println("is null");
}else{
System.out.println(users.toString());
}
} @Test
public void testUpdate() throws Exception {
User user = UserMapper.getOne(6l);
System.out.println(user.toString());
user.setName("dd");
UserMapper.update(user);
Assert.assertTrue(("dd".equals(UserMapper.getOne(6l).getName())));
} }
8、控制层
package com.example.demo.web; import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper; @RestController
public class UserController {
@Autowired
private UserMapper userMapper; @RequestMapping("/getUsers")
public List<User> getUsers() {
List<User> users=userMapper.getAll();
return users;
} @RequestMapping("/getUser")
public User getUser(Long id) {
User user=userMapper.getOne(id);
return user;
} @RequestMapping("/add")
public void save(User user) {
userMapper.insert(user);
} @RequestMapping(value="update")
public void update(User user) {
userMapper.update(user);
} @RequestMapping(value="/delete/{id}")
public void delete(@PathVariable("id") Long id) {
userMapper.delete(id);
}
}
项目目录结构:
二、使用XML
1、application.properties新增以下配置
mybatis.config-location = classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations = classpath:mybatis/mapper/*.xml
2、在resources/mybatis目录下添加mybatis-config.xml配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 控制台打印查询语句 -->
<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
<typeAliases>
<typeAlias alias="Integer" type="java.lang.Integer" />
<typeAlias alias="Long" type="java.lang.Long" />
<typeAlias alias="HashMap" type="java.util.HashMap" />
<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
<typeAlias alias="ArrayList" type="java.util.ArrayList" />
<typeAlias alias="LinkedList" type="java.util.LinkedList" />
</typeAliases>
</configuration>
3、添加映射文件UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.example.demo.entity.User" >
<id column="id" property="id" jdbcType="BIGINT" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="sex" property="sex" javaType="com.example.demo.enums.UserSexEnum"/>
</resultMap> <sql id="Base_Column_List" >
id, name, sex
</sql> <select id="getAll" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM user
</select> <select id="getOne" parameterType="java.lang.Long" resultMap="BaseResultMap" >
SELECT
<include refid="Base_Column_List" />
FROM user
WHERE id = #{id}
</select> <insert id="insert" parameterType="com.example.demo.entity.User" >
INSERT INTO
user
(name,sex)
VALUES
(#{name}, #{sex})
</insert> <update id="update" parameterType="com.example.demo.entity.User" >
UPDATE
user
SET
name = #{name}
WHERE
id = #{id}
</update> <delete id="delete" parameterType="java.lang.Long" >
DELETE FROM
user
WHERE
id =#{id}
</delete> </mapper>
4、编写Dao层的代码
package com.example.demo.mapper; import java.util.List; import com.example.demo.entity.User; public interface UserMapper { List<User> getAll(); User getOne(Long id); void insert(User user); void update(User user); void delete(Long id);
}
项目目录结构:
spring boot 2整合mybatis的更多相关文章
- Spring Boot:整合MyBatis框架
综合概述 MyBatis 是一款优秀的持久层框架,它支持定制化 SQL.存储过程以及高级映射.MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集.MyBatis 可以使用简单 ...
- Spring Boot 应用系列 3 -- Spring Boot 2 整合MyBatis和Druid,多数据源
本文演示多数据源(MySQL+SQL Server)的配置,并且我引入了分页插件pagehelper. 1. 项目结构 (1)db.properties存储数据源和连接池配置. (2)两个数据源的ma ...
- Spring Boot 应用系列 2 -- Spring Boot 2 整合MyBatis和Druid
本系列将分别演示单数据源和多数据源的配置和应用,本文先演示单数据源(MySQL)的配置. 1. pom.xml文件配置 需要在dependencies节点添加: <!-- MySQL --> ...
- Spring Boot中使用MyBatis注解配置详解(1)
之前在Spring Boot中整合MyBatis时,采用了注解的配置方式,相信很多人还是比较喜欢这种优雅的方式的,也收到不少读者朋友的反馈和问题,主要集中于针对各种场景下注解如何使用,下面就对几种常见 ...
- spring boot 2使用Mybatis多表关联查询
模拟业务关系:一个用户user有对应的一个公司company,每个用户有多个账户account. spring boot 2的环境搭建见上文:spring boot 2整合mybatis 一.mysq ...
- Spring Boot:整合Spring Security
综合概述 Spring Security 是 Spring 社区的一个顶级项目,也是 Spring Boot 官方推荐使用的安全框架.除了常规的认证(Authentication)和授权(Author ...
- Spring Boot:整合Swagger文档
综合概述 spring-boot作为当前最为流行的Java web开发脚手架,越来越多的开发者选择用其来构建企业级的RESTFul API接口.这些接口不但会服务于传统的web端(b/s),也会服务于 ...
- Spring Boot:实现MyBatis分页
综合概述 想必大家都有过这样的体验,在使用Mybatis时,最头痛的就是写分页了,需要先写一个查询count的select语句,然后再写一个真正分页查询的语句,当查询条件多了之后,会发现真的不想花双倍 ...
- Spring Boot:实现MyBatis动态数据源
综合概述 在很多具体应用场景中,我们需要用到动态数据源的情况,比如多租户的场景,系统登录时需要根据用户信息切换到用户对应的数据库.又比如业务A要访问A数据库,业务B要访问B数据库等,都可以使用动态数据 ...
随机推荐
- poj3723_Conscription
Conscription Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 12393 Accepted: 4350 Des ...
- CString 成员函数用法
参考文档:http://www.cnblogs.com/Caiqinghua/archive/2009/02/16/1391190.html CString的构造函数CString( );例:CStr ...
- nginx 禁止恶意域名解析
server { listen default_server; server_name _; ssl on; ssl_certificate /etc/nginx/cert/aaaa.pem; ssl ...
- If 与 else的性福生活。
IF 与 ELSE 从此不再孤单 今天我们来学习java课程里的选择结构——if与else if的意思,众所周知,就是如果想必大家心里对这个词已经有丶数了 else的意思,一目了然,就是否则经过图片的 ...
- php利用OpenXML规范生成word,excel(pdf其他方法)
这个涉及到的东西比较多 HTTP MIME types $contract_data = '<html xmlns:o="urn:schemas-microsoft-com:offic ...
- Mock Server 入门(一)
Mock Server 使用场景 1.开发过程中依赖一些接口,而这些接口可能有一下情况: 1)接口搭建环境比较困难:例如支付宝的支付接口,需要授权等等准备好才能进行调试 2)接口暂时还未实现时:可以便 ...
- qt opencv编译错误 /usr/local/lib/libopencv_imgcodecs.so.3.1:-1: error: error adding symbols: DSO missing from command line
转载自:http://tbfungeek.github.io/2016/03/05/Opencv-%E5%AE%89%E8%A3%85%E8%BF%87%E7%A8%8B%E4%B8%AD%E5%87 ...
- IIC - 【转载】对I2C总线的时钟同步和总线仲裁的深入理解
对I2C总线的时钟同步和总线仲裁的深入理解 每一个IIC总线器件内部的SDA.SCL引脚电路结构都是一样的,引脚的输出驱动与输入缓冲连在一起.其中输出为漏极开路的场效应管.输入缓冲为一只高输入阻抗的同 ...
- stellar.js 视差滚动
1.引入包 <script src="js/jquery.min.js"></script> <script src="js/jquery. ...
- git忽略规则.gitignore未生效解决办法
创建git本地的仓库常用命令:git init #初始化--------生成.git文件 配置本地用户名跟邮箱(这样就知道是谁提交的东西)git config --global user.name [ ...