此文已由作者赵计刚薪授权网易云社区发布。
欢迎访问网易云社区,了解更多网易技术产品运营经验。
springboot集成了springJDBC与JPA,但是没有集成mybatis,所以想要使用mybatis就要自己去集成。集成方式相当简单。
1、项目结构
2、pom.xml
1 <!-- 与数据库操作相关的依赖 --> 2 <dependency> 3 <groupId>org.springframework.boot</groupId> 4 <artifactId>spring-boot-starter-jdbc</artifactId> 5 </dependency> 6 7 <!-- 使用数据源 --> 8 <dependency> 9 <groupId>com.alibaba</groupId> 10 <artifactId>druid</artifactId> 11 <version>1.0.14</version> 12 </dependency> 13 14 <!-- mysql --> 15 <dependency> 16 <groupId>mysql</groupId> 17 <artifactId>mysql-connector-java</artifactId> 18 <scope>runtime</scope> 19 </dependency> 20 21 <!-- mybatis --> 22 <dependency> 23 <groupId>org.mybatis</groupId> 24 <artifactId>mybatis</artifactId> 25 <version>3.2.8</version> 26 </dependency> 27 <dependency> 28 <groupId>org.mybatis</groupId> 29 <artifactId>mybatis-spring</artifactId> 30 <version>1.2.2</version> 31 </dependency>
说明:
spring-boot-starter-jdbc:引入与数据库操作相关的依赖,例如daoSupport等
3、application.properties
1 jdbc.driverClassName = com.mysql.jdbc.Driver 2 jdbc.url = jdbc:mysql://xxx:3306/mytestdb?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8 3 jdbc.username = root 4 jdbc.password = vvvxxx 5 6 mybatis.typeAliasesPackage=com.xxx.firstboot.domain 7 mybatis.mapperLocations=classpath:mapper/*.xml
说明:
mybatis.mapperLocations:指定*Mapper.xml的位置
4、com.xxx.firstboot.common.MyBatisConfig
作用:mybatis与springboot集成的入口
1 package com.xxx.firstboot.common; 2 3 import java.util.Properties; 4 5 import javax.sql.DataSource; 6 7 import org.apache.ibatis.session.SqlSessionFactory; 8 import org.mybatis.spring.SqlSessionFactoryBean; 9 import org.mybatis.spring.annotation.MapperScan; 10 import org.springframework.beans.factory.annotation.Autowired; 11 import org.springframework.context.annotation.Bean; 12 import org.springframework.context.annotation.Configuration; 13 import org.springframework.core.env.Environment; 14 import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 15 16 import com.alibaba.druid.pool.DruidDataSourceFactory; 17 18 /** 19 * springboot集成mybatis的基本入口 20 * 1)创建数据源 21 * 2)创建SqlSessionFactory 22 */ 23 @Configuration //该注解类似于spring配置文件 24 @MapperScan(basePackages="com.xxx.firstboot.mapper") 25 public class MyBatisConfig { 26 27 @Autowired 28 private Environment env; 29 30 /** 31 * 创建数据源 32 * @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错 33 */ 34 @Bean 35 //@Primary 36 public DataSource getDataSource() throws Exception{ 37 Properties props = new Properties(); 38 props.put("driverClassName", env.getProperty("jdbc.driverClassName")); 39 props.put("url", env.getProperty("jdbc.url")); 40 props.put("username", env.getProperty("jdbc.username")); 41 props.put("password", env.getProperty("jdbc.password")); 42 return DruidDataSourceFactory.createDataSource(props); 43 } 44 45 /** 46 * 根据数据源创建SqlSessionFactory 47 */ 48 @Bean 49 public SqlSessionFactory sqlSessionFactory(DataSource ds) throws Exception{ 50 SqlSessionFactoryBean fb = new SqlSessionFactoryBean(); 51 fb.setDataSource(ds);//指定数据源(这个必须有,否则报错) 52 //下边两句仅仅用于*.xml文件,如果整个持久层操作不需要使用到xml文件的话(只用注解就可以搞定),则不加 53 fb.setTypeAliasesPackage(env.getProperty("mybatis.typeAliasesPackage"));//指定基包 54 fb.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(env.getProperty("mybatis.mapperLocations")));//指定xml文件位置 55 56 return fb.getObject(); 57 } 58 59 }
说明:
这样之后,在项目中再使用springboot就和在ssm中(配置完成后)使用一样了。
5、com.xxx.firstboot.mapper.UserMapper
说明:该接口中有两个方法,
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 4 <!-- 指定工作空间,要与接口名相同,源代码没有去看,猜测应该是通过"这里的namespace.下边方法的id"来定位方法的 --> 5 <mapper namespace="com.xxx.firstboot.mapper.UserMapper"> 6 7 <!-- 若不需要自动返回主键,将useGeneratedKeys="true" keyProperty="id"去掉即可(当然如果不需要自动返回主键,直接用注解即可) --> 8 <insert id="insertUserWithBackId" parameterType="User" useGeneratedKeys="true" keyProperty="id" > 9 <![CDATA[ 10 INSERT INTO tb_user 11 ( 12 username, 13 password 14 ) 15 VALUES 16 ( 17 #{username, jdbcType=VARCHAR}, 18 #{password, jdbcType=VARCHAR} 19 ) 20 ]]> 21 </insert> 22 23 </mapper>
6、com.xxx.firstboot.dao.UserDao
1 package com.xxx.firstboot.dao; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Repository; 5 6 import com.xxx.firstboot.domain.User; 7 import com.xxx.firstboot.mapper.UserMapper; 8 9 @Repository 10 public class UserDao { 11 12 @Autowired 13 private UserMapper userMapper; 14 15 public int insertUser(String username, String password){ 16 return userMapper.insertUser(username, password); 17 } 18 19 public int insertUserWithBackId(User user){ 20 return userMapper.insertUserWithBackId(user); 21 } 22 23 }
7、com.xxx.firstboot.service.UserService
1 package com.xxx.firstboot.service; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.stereotype.Service; 5 6 import com.xxx.firstboot.dao.UserDao; 7 import com.xxx.firstboot.domain.User; 8 9 @Service 10 public class UserService { 11 12 @Autowired 13 private UserDao userDao; 14 15 public boolean addUser(String username, String password){ 16 return userDao.insertUser(username, password)==1?true:false; 17 } 18 19 public User addUserWithBackId(String username, String password){ 20 User user = new User(); 21 user.setUsername(username); 22 user.setPassword(password); 23 userDao.insertUserWithBackId(user);//该方法后,主键已经设置到user中了 24 return user; 25 } 26 27 }
8、com.xxx.firstboot.controller.UserController
1 package com.xxx.firstboot.web; 2 3 import org.springframework.beans.factory.annotation.Autowired; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.RequestMethod; 6 import org.springframework.web.bind.annotation.RequestParam; 7 import org.springframework.web.bind.annotation.RestController; 8 9 import com.xxx.firstboot.domain.User; 10 import com.xxx.firstboot.service.UserService; 11 12 import io.swagger.annotations.Api; 13 import io.swagger.annotations.ApiImplicitParam; 14 import io.swagger.annotations.ApiImplicitParams; 15 import io.swagger.annotations.ApiOperation; 16 import io.swagger.annotations.ApiResponse; 17 import io.swagger.annotations.ApiResponses; 18 19 @RestController 20 @RequestMapping("/user") 21 @Api("userController相关api") 22 public class UserController { 23 24 @Autowired 25 private UserService userService; 26 27 @ApiOperation("添加用户") 28 @ApiImplicitParams({ 29 @ApiImplicitParam(paramType="query",name="username",dataType="String",required=true,value="用户的姓名",defaultValue="zhaojigang"), 30 @ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="用户的密码",defaultValue="wangna") 31 }) 32 @ApiResponses({ 33 @ApiResponse(code=400,message="请求参数没填好"), 34 @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对") 35 }) 36 @RequestMapping(value="/addUser",method=RequestMethod.POST) 37 public boolean addUser(@RequestParam("username") String username, 38 @RequestParam("password") String password) { 39 return userService.addUser(username,password); 40 } 41 42 @ApiOperation("添加用户且返回已经设置了主键的user实例") 43 @ApiImplicitParams({ 44 @ApiImplicitParam(paramType="query",name="username",dataType="String",required=true,value="用户的姓名",defaultValue="zhaojigang"), 45 @ApiImplicitParam(paramType="query",name="password",dataType="String",required=true,value="用户的密码",defaultValue="wangna") 46 }) 47 @ApiResponses({ 48 @ApiResponse(code=400,message="请求参数没填好"), 49 @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对") 50 }) 51 @RequestMapping(value="/addUserWithBackId",method=RequestMethod.POST) 52 public User addUserWithBackId(@RequestParam("username") String username, 53 @RequestParam("password") String password) { 54 return userService.addUserWithBackId(username, password); 55 } 56 }
测试:
进入项目的pom.xml文件所在目录,执行"mvn spring-boot:run"(这是最推荐的spring-boot的运行方式),另外一种在主类上右击-->"run as"-->"java application"不常用
参考自:
http://www.111cn.net/jsp/Java/93604.htm :springboot+mybatis+多数据源
http://blog.csdn.net/xiaoyu411502/article/details/48164311:springboot+mybatis+读写分离(其实读写分离就是两个数据源对两个库进行操作)
免费领取验证码、内容安全、短信发送、直播点播体验包及云服务器等套餐
更多网易技术、产品、运营经验分享请点击。