【Spring Boot 十一】 MyBatis 连接数据库
最近比较忙,没来得及抽时间把MyBatis的集成发出来,其实mybatis官网在2015年11月底就已经发布了对SpringBoot集成的Release版本,Github上有代码:https://github.com/mybatis/mybatis-spring-boot
前面对JPA和JDBC连接数据库做了说明,本文也是参考官方的代码做个总结。
关于在Spring Boot中集成MyBatis,可以选用基于注解的方式,也可以选择xml文件配置的方式。通过对两者进行实际的使用,个人建议使用XML的方式(官方也建议使用XML)
通过xml配置文件方式
1、添加pom依赖
1 2 3 4 5 |
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.2.0</version> </dependency> |
2、创建UserDao和UserDao.xml
UserDao.java
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.spring.boot.dao; import com.spring.boot.entity.User; import org.apache.ibatis.annotations.Param; /** * UserDao * Created by XJH on 2017/8/29. */ public interface UserDao { User getUserById(@Param("id") Integer id); } |
3、创建UserService和userServiceImpl
UserService.java
1 2 3 4 5 6 7 8 9 10 11 |
package com.spring.boot.service; import com.spring.boot.entity.User; /** * UserService * Created by XJH on 2017/8/31. */ public interface UserService { User getUserById(Integer id); } |
UserServiceImpl.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.spring.boot.service.impl; import com.spring.boot.dao.UserDao; import com.spring.boot.entity.User; import com.spring.boot.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * UserServiceImpl * Created by XJH on 2017/8/31. */ @Service public class UserServiceImpl implements UserService { private final UserDao userDao; @Autowired public UserServiceImpl(UserDao userDao) { this.userDao = userDao; } @Override public User getUserById(Integer id) { return userDao.getUserById(id); } } |
4、创建UserController
UserController.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.spring.boot.web; import com.spring.boot.entity.User; import com.spring.boot.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; /** * UserController * Created by XJH on 2017/8/31. */ @RestController @RequestMapping("/user") public class UserController { private final UserService userService; @Autowired public UserController(UserService userService) { this.userService = userService; } @GetMapping(produces = {"application/json;charset=UTF-8"}) public User getUserById(Integer id){ return userService.getUserById(id); } } |
5、创建UserDao.xml
/main/resources/mapper/UserDao.xml
1 2 3 4 5 6 7 8 |
<?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.spring.boot.dao.UserDao"> <select id="getUserById" resultType="com.spring.boot.entity.User"> select * from user where id = #{id}; </select> </mapper> |
6、创建一个XML(不然类似于数据库字段create_time无法映射到实体类createTime)
/main/resources/mybatis-config.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?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="defaultStatementTimeout" value="3000"/> <setting name="useColumnLabel" value="true"/> <setting name="mapUnderscoreToCamelCase" value="true"/> <setting name="useGeneratedKeys" value="true"/> </settings> <!-- Continue going here --> </configuration> |
7、在application.properties添加如下信息
1 2 3 4 |
#MyBatis mybatis.mapper-locations=classpath:mapper/*.xml mybatis.type-aliases-package=com.spring.boot.entity mybatis.config-location=classpath:mybatis-config.xml |
8、在启动项目SpringBootSimpleApplication中添加如下注解:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
package com.spring.boot; import org.mybatis.spring.annotation.MapperScan; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; /** * SpringBootSampleApplication * Created by XJH on 2017/8/22. */ @SpringBootApplication @ServletComponentScan @MapperScan("com.spring.boot.dao") //配置扫描mapper接口的地址 public class SpringBootSampleApplication { private static Logger logger= LoggerFactory.getLogger(SpringBootSampleApplication.class); public static void main(String[] args) { SpringApplication.run(SpringBootSampleApplication.class, args); logger.info("SpringBoot Start Success"); } } |
到这里我们的 spring boot 整合 mybatis 算是完成了。
测试
启动项目
访问:http://localhost:8080/spring_boot/user?id=1 (在controller可以看到访问路径)
结果:
{"id":1,"name":"xjh","age":99,"profile":"xjh个人简介","password":"xjh的密码","salt":"xjh的salt","createTime":1504694109000,"updateTime":1504694167000}
(在前面说过了,如果不加入mybatis-config.xml的话这个createTime和updateTime就是null)
使用注解方式
可以看一下mybatis官方的demo:https://github.com/mybatis/mybatis-spring-boot
配置上很简单,使用上要对注解多做了解。至于xml和注解这两种哪种方法好,众口难调还是要看每个人吧。我个人比较喜欢xml方式。
UserDao.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.spring.boot.dao; import com.spring.boot.entity.User; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; /** * UserDao * Created by XJH on 2017/8/29. */ public interface UserDao { @Select("SELECT * FROM User WHERE id = #{id}") User getUserById(@Param("id") Integer id); } |
关于MaBatis基于注解的方式,有一篇博文讲的很清楚,可以看看http://blog.csdn.net/luanlouis/article/details/35780175
下一篇 spring boot 整合shiro。
意志坚强的人,他的世界充满着无限的可能性。
fap
Ԝhat's uup to every , since I am actually eager oof reading tһіs
web site's post tߋ be updated regularly. Ιt incluԁes nice informɑtion.
fap
After going over a handful of the blog posts on уour website, I honestly aplpreciate
youг ѡay of writing a blog. I savewd ass а favorite іt
to mʏ bookmark site llist and ѡill be checking bɑck sօߋn. Pleɑѕe visit my web site ɑs wеll
and let me know whazt you think.
fap
Ι thіnk tһis іs among thhe most vital infoгmation for mе.
Αnd i аm glad reading үօur article. Bսt wanna remark on fеᴡ geeral tһings, The web site style is wonderful,
the articles iѕ rreally nice : D. Good job, cheers
aliyun.com
Pretty! This wɑs a realⅼy wonderful post. Τhank you for providing
this info.