zoukankan      html  css  js  c++  java
  • 第五章 springboot + mybatis(转载)

    本编博客转发自:http://www.cnblogs.com/java-zhao/p/5350021.html

    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>
    View Code

    说明:

    • spring-boot-starter-jdbc:引入与数据库操作相关的依赖,例如daoSupport等

    • druid:阿里巴巴的数据源
    • mysql-connector-java:mysql连接jar,scope为runtime
    • mybatis + mybatis-spring:mybatis相关jar

    3、application.properties

    jdbc.driverClassName = com.mysql.jdbc.Driver
    jdbc.url = jdbc:mysql://xxx:3306/mytestdb?zeroDateTimeBehavior=convertToNull&amp;useUnicode=true&amp;characterEncoding=utf-8
    jdbc.username = root
    jdbc.password = vvvxxx
    
    mybatis.typeAliasesPackage=com.xxx.firstboot.domain  
    mybatis.mapperLocations=classpath:mapper/*.xml
    View Code

    说明:

    • mybatis.typeAliasesPackage:指定domain类的基包,即指定其在*Mapper.xml文件中可以使用简名来代替全类名(看后边的UserMapper.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 }
    View Code

    说明:

    • 类上边添加两个
      • @Configuration注解(该注解类似于spring的配置文件)
      • @MapperScan注解,指定扫描的mapper接口所在的包
    • 在该类中,注入了Environment实例,使用该实例可以去读取类路径下application.properties文件中的内容,读取文件内容的三种方式,见第二章 第二个spring-boot程序
    • 在该类中,使用druid数据源定义了数据源Bean,spring-boot默认使用的是tomcat-jdbc数据源,这是springboot官方推荐的数据源(性能和并发性都很好)
    • 根据数据源生成SqlSessionFactory
      • 值得注意的是,数据源是必须指定的,否则springboot启动不了
      • typeAliasesPackage和mapperLocations不是必须的,如果整个项目不需要用到*Mapper.xml来写SQL的话(即只用注解就可以搞定),那么不需要配
    • @Primary注解:指定在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@Autowire注解报错(一般用于多数据源的情况下)

    这样之后,在项目中再使用springboot就和在ssm中(配置完成后)使用一样了。

    5、com.xxx.firstboot.mapper.UserMapper

     1 package com.xxx.firstboot.mapper;
     2 
     3 import org.apache.ibatis.annotations.Insert;
     4 import org.apache.ibatis.annotations.Param;
     5 
     6 import com.xxx.firstboot.domain.User;
     7 
     8 public interface UserMapper {
     9     
    10     @Insert("INSERT INTO tb_user(username, password) VALUES(#{username},#{password})")
    11     public int insertUser(@Param("username") String username, @Param("password")  String password);
    12     
    13     /**
    14      * 插入用户,并将主键设置到user中
    15      * 注意:返回的是数据库影响条数,即1
    16      */
    17     public int insertUserWithBackId(User user);
    18 }
    View Code

    说明:该接口中有两个方法,

    • 一个普通插入:直接用注解搞定
    • 一个插入返回主键:需要使用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">
    
    <!-- 指定工作空间,要与接口名相同,源代码没有去看,猜测应该是通过"这里的namespace.下边方法的id"来定位方法的 -->
    <mapper namespace="com.xxx.firstboot.mapper.UserMapper">
        
        <!-- 若不需要自动返回主键,将useGeneratedKeys="true" keyProperty="id"去掉即可(当然如果不需要自动返回主键,直接用注解即可) -->
        <insert id="insertUserWithBackId" parameterType="User" useGeneratedKeys="true" keyProperty="id" >
           <![CDATA[
           INSERT INTO tb_user 
           (
               username,
               password
           )
           VALUES
           (
               #{username, jdbcType=VARCHAR},
               #{password, jdbcType=VARCHAR}
           )
           ]]>
       </insert>
        
    </mapper>
    View Code

    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 }
    View Code

    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 }
    View Code

    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 }
    View Code

    测试:

    进入项目的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+读写分离(其实读写分离就是两个数据源对两个库进行操作)

  • 相关阅读:
    深入admin之chang_list
    List<T>列表通用过滤模块设计
    Mysql行转换为列
    Linux中cp直接覆盖不提示的方法
    hibernate Restrictions 用法
    java.lang.OutOfMemoryError: PermGen space
    ruby+gem常用命令
    Linux查看CPU和内存使用情况
    在Ubuntu 9.04下配置Apache和ModPython
    有关查询和执行计划的DMV 从而明确那些SQL要优化
  • 原文地址:https://www.cnblogs.com/jian-xiao/p/6048844.html
Copyright © 2011-2022 走看看