springboot【13】数据访问之整合Mybatis
2017-08-08 15:02
736 查看
本文详细介绍如何在Spring Boot中整合MyBatis,并通过注解方式实现映射,更多其他注解的使用可参见文档:http://www.mybatis.org/mybatis-3/zh/java-api.html
一、整合MyBatis
pom.xml中引入依赖
spring-boot-starter基础和spring-boot-starter-test单元测试验证数据访问
引入连接mysql的必要依赖mysql-connector-java
引入整合MyBatis的核心依赖mybatis-spring-boot-starter
无需引入spring-boot-starter-jdbc依赖,由于mybatis-spring-boot-starter中已经包含了此依赖
<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.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency>
同之前介绍的使用jdbc和spring-data连接数据库一样,在
application.properties中配置mysql的连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/springboot spring.datasource.username=root spring.datasource.password=root spring.datasource.driver-class-name=com.mysql.jdbc.Driver
二、简单使用MyBatis
创建Spring Boot主类package com.lyd; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
在Mysql中创建User表,包含id(BIGINT)、name(VARCHAR)、age(INT)字段。同时,创建映射对象User
package com.lyd.domain; public class User { private Long id; private String name; private Integer age; // 构造函数 // get/set方法... }
创建User映射的操作UserMapper,为了后续单元测试验证,实现插入和查询操作
package com.lyd.domain; import org.apache.ibatis.annot 4000 ations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; @Mapper public interface UserMapper { @Select("SELECT * FROM USER WHERE NAME = #{name}") User findByName(@Param("name") String name); @Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})") int insert(@Param("name") String name, @Param("age") Integer age); }
创建单元测试
测试逻辑:插入一条name=AAA,age=20的记录,然后根据name=AAA查询,并判断age是否为20
测试结束回滚数据,保证测试单元每次运行的数据环境独立
package com.lyd; 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.SpringApplicationConfiguration; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.lyd.domain.User; import com.lyd.domain.UserMapper; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(Application.class) public class ApplicationTest { @Autowired private UserMapper userMapper; @Test @Rollback public void fingByName(){ userMapper.insert("aaa", 10); User u = userMapper.findByName("aaa"); Assert.assertEquals(100, u.getAge().intValue()); } }
三、Mybatis注解配置详解
1.传参方式
下面通过几种不同传参方式来实现上文中实现的插入操作。(1)使用@Param
在之前的整合示例中我们已经使用了这种最简单的传参方式,如下:@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})") int insert(@Param("name") String name, @Param("age") Integer age);这种方式很好理解,
@Param中定义的
name对应了SQL中的
#{name},
age对应了SQL中的
#{age}。
(2)使用Map
如下代码,通过Map对象来作为传递参数的容器:@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})") int insertByMap(Map<String, Object> map);
对于Insert语句中需要的参数,测试时只需要在map中填入同名的内容即可,具体如下面代码所示:
Map<String, Object> map = new HashMap<>(); map.put("name", "CCC"); map.put("age", 40); userMapper.insertByMap(map);
(3)使用对象
除了Map对象,我们也可直接使用普通的Java对象来作为查询条件的传参,比如我们可以直接使用User对象:@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})") int insertByUser(User user);
这样语句中的
#{name}、
#{age}就分别对应了User对象中的
name和
age属性。
2.增删改查
MyBatis针对不同的数据库操作分别提供了不同的注解来进行配置,下面针对User表做一组最基本的增删改查作为示例:package com.lyd.domain;
import java.util.Map;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM USER WHERE NAME = #{name}")
User findByName(@Param("name") String name);
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})") int insert(@Param("name") String name, @Param("age") Integer age);
@Update("UPDATE user SET age=#{age} WHERE name=#{name}")
void update(User user);
@Delete("DELETE FROM user WHERE id = #{id}")
void delete(Long id);
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})") int insertByMap(Map<String, Object> map);
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})") int insertByUser(User user);
}
单元测试来验证上面操作的正确性:
package com.lyd; import java.util.HashMap; import java.util.Map; 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.SpringApplicationConfiguration; import org.springframework.test.annotation.Rollback; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.lyd.domain.User; import com.lyd.domain.UserMapper; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(Application.class) public class ApplicationTest { @Autowired private UserMapper userMapper; @Test @Rollback public void testUserMapper(){ // insert一条数据,并select出来验证 userMapper.insert("aaa", 10); User u = userMapper.findByName("aaa"); Assert.assertEquals(10, u.getAge().intValue()); // update一条数据,并select出来验证 u.setAge(20); userMapper.update(u); u = userMapper.findByName("aaa"); Assert.assertEquals(20, u.getAge().intValue()); // 删除这条数据,并select验证 userMapper.delete(u.getId()); u = userMapper.findByName("aaa"); Assert.assertEquals(null, u); u = new User("bbb",30); userMapper.insertByUser(u); Assert.assertEquals(30, userMapper.findByName("bbb").getAge().intValue()); Map<String, Object> map = new HashMap<>(); map.put("name", "ccc"); map.put("age", 40); userMapper.insertByMap(map); Assert.assertEquals(40, userMapper.findByName("ccc").getAge().intValue()); } }
3.返回结果的绑定
对于增、删、改操作相对变化较小。而对于“查”操作,我们往往需要进行多表关联,汇总计算等操作,那么对于查询的结果往往就不再是简单的实体对象了,往往需要返回一个与数据库实体不同的包装类,那么对于这类情况,就可以通过@Results和
@Result注解来进行绑定,具体如下:
@Results({ @Result(property = "name", column = "name"), @Result(property = "age", column = "age") }) @Select("SELECT name, age FROM user") List<User> findAll();
在上面代码中,@Result中的property属性对应User对象中的成员名,column对应SELECT出的字段名。在该配置中故意没有查出id属性,只对User对应中的name和age对象做了映射配置,这样可以通过下面的单元测试来验证查出的id为null,而其他属性不为null:
@Test @Rollback public void testUserMapper() throws Exception { List<User> userList = userMapper.findAll(); for(User user : userList) { Assert.assertEquals(null, user.getId()); Assert.assertNotEquals(null, user.getName()); } }
下面是完整项目结构:
相关文章推荐
- Spring boot之数据访问及mybatis整合(三)
- Spring+SpringMVC+MyBatis+easyUI整合优化篇(十一)数据层优化-druid监控及慢sql记录
- JavaEE Tutorials (13) - 使用锁定控制对实体数据的并发访问
- java鬼混笔记:springboot 7、springboot整合mybatis后再加上druid数据库连接池
- SpringBoot的数据访问
- springboot 整合freemaker+mybatis
- springboot-27-整合mybatis,druid连接池
- SpringMVC+Spring+MyBatis整合完整版Web实例(附数据)
- springboot整合mybatis
- java鬼混笔记:springboot 9、springboot整合mybatis加上分页功能
- SpringBoot整合Mybatis
- springboot和mybatis整合(二)
- SpringBoot整合MyBatis
- Spring Boot与Spring Security整合后post数据不了,403拒绝访问
- SpringBoot 整合 MyBatis 及引入事务
- springboot项目使用注解法整合mybatis的具体步骤
- 【SpringMVC整合MyBatis】数据回显
- [置顶] springboot整合mybatis方式一
- CDH5.8手动安装spark2.1的运行错误整合 spark访问Hbase 数据导入mysql