分享

spring-boot 集成mybatis配置使用

 青_春 2018-03-14

基本照搬了mybatis-spring-boot-samples中的代码,先上手。

添加maven依赖

在pom文件中增加如下内容

[java] view plain copy
  1. <dependency>  
  2.       <groupId>org.mybatis.spring.boot</groupId>  
  3.       <artifactId>mybatis-spring-boot-starter</artifactId>  
  4.       <version>1.1.1</version>  
  5. </dependency>  

创建表

在数据库中增加一张表用于测试,以下是建表语句

  1. CREATE TABLE `user` (  
  2.   `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',  
  3.   `namevarchar(128) DEFAULT NULL,  
  4.   `money` decimal(10,2) DEFAULT NULL,  
  5.   `create_date` datetime NOT NULL,  
  6.   `modify_date` datetime NOT NULL,  
  7.   `is_deleted` tinyint(4) NOT NULL,  
  8.   PRIMARY KEY (`id`)  
  9. ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户';  

添加相关配置信息

首先在resources目录下增加mybatis-config.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE configuration  
  3.         PUBLIC "-////DTD Config 3.0//EN"  
  4.         "http:///dtd/mybatis-3-config.dtd">  
  5. <configuration>  
  6.     <mappers>  
  7.         <mapper resource="mybatis/mapper/UserMapper.xml"/>  
  8.     </mappers>  
  9. </configuration>  
在resources目录下创建mybatis/mapper目录,并在其下创建UserMapper.xml

[html] view plain copy
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper  
  3.         PUBLIC "-////DTD Mapper 3.0//EN"  
  4.         "http:///dtd/mybatis-3-mapper.dtd">  
  5. <mapper namespace="com.mapper.UserMapper">  
  6.     <resultMap id="BaseResultMap" type="com.model.UserMo">  
  7.         <id column="id" jdbcType="BIGINT" property="id" />  
  8.         <result column="name" jdbcType="VARCHAR" property="name" />  
  9.         <result column="money" jdbcType="DECIMAL" property="money" />  
  10.         <result column="create_date" jdbcType="TIMESTAMP" property="createDate" />  
  11.         <result column="modify_date" jdbcType="TIMESTAMP" property="modifyDate" />  
  12.         <result column="is_deleted" jdbcType="TINYINT" property="isDeleted" />  
  13.     </resultMap>  
  14.     <select id="selectUserById" resultMap="BaseResultMap">  
  15.         select * from test_user where id = #{id}  
  16.     </select>  
  17. </mapper>  

在application.propertise文件中添加以下配置,指定mybatis-config.xml的位置

[plain] view plain copy
  1. mybatis.config-location=classpath:mybatis-config.xml  
如果在application.propertise文件中添加以下配置,则mybatis-config.xml无需再配置<mappers></mappers>中的内容

[plain] view plain copy
  1. mybatis.mapper-locations=classpath:mybatis/mapper/*Mapper.xml  

相关java代码

创建表user对应的实体类UserMo.java

[java] view plain copy
  1. package com.model;  
  2.   
  3. import java.math.BigDecimal;  
  4. import java.util.Date;  
  5.   
  6. public class UserMo {  
  7.   
  8.     private Long id;  
  9.     private String name;  
  10.     private BigDecimal money;  
  11.     private Date createDate;  
  12.     private Date modifyDate;  
  13.     private Integer isDeleted;  
  14.   
  15.     public Long getId() {  
  16.         return id;  
  17.     }  
  18.   
  19.     public void setId(Long id) {  
  20.         this.id = id;  
  21.     }  
  22.   
  23.     public String getName() {  
  24.         return name;  
  25.     }  
  26.   
  27.     public void setName(String name) {  
  28.         this.name = name;  
  29.     }  
  30.   
  31.     public BigDecimal getMoney() {  
  32.         return money;  
  33.     }  
  34.   
  35.     public void setMoney(BigDecimal money) {  
  36.         this.money = money;  
  37.     }  
  38.   
  39.     public Date getCreateDate() {  
  40.         return createDate;  
  41.     }  
  42.   
  43.     public void setCreateDate(Date createDate) {  
  44.         this.createDate = createDate;  
  45.     }  
  46.   
  47.     public Date getModifyDate() {  
  48.         return modifyDate;  
  49.     }  
  50.   
  51.     public void setModifyDate(Date modifyDate) {  
  52.         this.modifyDate = modifyDate;  
  53.     }  
  54.   
  55.     public Integer getIsDeleted() {  
  56.         return isDeleted;  
  57.     }  
  58.   
  59.     public void setIsDeleted(Integer isDeleted) {  
  60.         this.isDeleted = isDeleted;  
  61.     }  
  62. }  

创建对应的UserMapper.java

[java] view plain copy
  1. package com.mapper;  
  2.   
  3. import com.model.UserMo;  
  4. import org.apache.ibatis.annotations.Mapper;  
  5. import org.apache.ibatis.annotations.Param;  
  6.   
  7. @Mapper  
  8. public interface UserMapper {  
  9.   
  10.     UserMo selectUserById(@Param("id") Long id);  
  11. }  
创建UserDao.java

[java] view plain copy
  1. package com.dao;  
  2.   
  3. import com.model.UserMo;  
  4. import org.apache.ibatis.session.SqlSession;  
  5. import org.springframework.stereotype.Component;  
  6.   
  7. @Component  
  8. public class UserDao {  
  9.   
  10.     private final SqlSession sqlSession;  
  11.   
  12.     public UserDao(SqlSession sqlSession) {  
  13.         this.sqlSession = sqlSession;  
  14.     }  
  15.   
  16.     public UserMo findUserById(Long id) {  
  17.         return this.sqlSession.selectOne("selectUserById", id);  
  18.     }  
  19. }  

测试

OK,准备工作都已就绪,开始测试,增加如下内容

[java] view plain copy
  1. @Autowired  
  2. private UserMapper userMapper;  
  3. @Autowired  
  4. private UserDao userDao;  
  5.   
  6. @RequestMapping("/find/mybatis/id")  
  7. public String findMailByToFromMybatis(HttpServletRequest request, Long id) {  
  8.     UserMo userMo = userMapper.selectUserById(id);  
  9.     UserMo userMo1 = userDao.findUserById(id);  
  10.     return "userMapper: " + JSON.toJSONString(userMo) + ", userDao: " + JSON.toJSONString(userMo1);  
  11. }  
启动项目,在浏览器中输入http://127.0.0.1:8080/find/mybatis/id?id=1,会看到如下

[java] view plain copy
  1. userMapper: {"createDate":1483586613000,"id":1,"isDeleted":0,"modifyDate":1483586613000,"money":1.20,"name":"sss"}   
  2. userDao: {"createDate":1483586613000,"id":1,"isDeleted":0,"modifyDate":1483586613000,"money":1.20,"name":"sss"}  
而且在控制台看到如下输出

[plain] view plain copy
  1. INFO 1238 --- [nio-8080-exec-1] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited  
  2. [http-nio-8080-exec-1] INFO  c.alibaba.druid.pool.DruidDataSource - {dataSource-1} inited  
可以看到用的连接池正是之前配置的druid连接池。


其中很多代码入model,mapper等可以通过mybatis的逆向工程直接生成。

另一种方式

使用Mapper注解,不需要对应的mapper.xml文件,创建UserMapper1.java

[java] view plain copy
  1. package com.mapper;  
  2.   
  3. import com.model.UserMo;  
  4. import org.apache.ibatis.annotations.Mapper;  
  5. import org.apache.ibatis.annotations.Param;  
  6. import org.apache.ibatis.annotations.Select;  
  7.   
  8. @Mapper  
  9. public interface UserMapper1 {  
  10.   
  11.     @Select("select id, name, money, create_date as createDate, modify_date as modifyDate, is_deleted as isDeleted" +  
  12.             " from test_user where name = #{name}")  
  13.     UserMo selectUserByName(@Param("name") String name);  
  14. }  
其中部分字段使用了别名,不这样的话无法得到其中的内容。

测试代码如下

[java] view plain copy
  1. @Autowired  
  2. private UserMapper1 userMapper1;  
  3.   
  4. @RequestMapping("/find/mybatis/name")  
  5. public String findMailByToFromMybatis(HttpServletRequest request, String name) {  
  6.     UserMo userMo = userMapper1.selectUserByName(name);  
  7.     return "userMapper1: " + JSON.toJSONString(userMo);  
  8. }  
启动服务后,输入http://127.0.0.1:8080/find/mybatis/name?name=sss,可以看到如下内容

[plain] view plain copy
  1. userMapper1: {"createDate":1483586613000,"id":1,"isDeleted":0,"modifyDate":1483586613000,"money":1.20,"name":"sss"}  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多