• SpringBoot学习笔记4-整合Jdbc Template-Mybatis-多数据源-事务管理-JPA


    二十三 SpringBoot整合JdbcTemplate

    23.1 添加相关依赖(已经添加了spring-boot-starter-web)

     1          <!-- JdbcTemplate的依賴 -->
     2        <dependency>
     3             <groupId>org.springframework.boot</groupId>
     4             <artifactId>spring-boot-starter-jdbc</artifactId>
     5        </dependency>
     6        
     7        <!-- mysql依賴 -->
     8        <dependency>
     9                <groupId>mysql</groupId>
    10                <artifactId>mysql-connector-java</artifactId>
    11        </dependency>        
    JdbcTemplate和mysql的依赖

    23.2 在全局配置文件中配置相关数据库连接属性

    1 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    2 spring.datasource.username=root
    3 #自己的密码
    4 spring.datasource.password=root
    5 #自己定义的数据库名
    6 spring.datasource.url=jdbc:mysql://localhost:3306/springboot
    连接数据库配置

    23.3 数据库中创建一个用户表,并编写实体类

     1 /*
     2 Navicat MySQL Data Transfer
     3 
     4 Source Server         : localhost_3306
     5 Source Server Version : 50549
     6 Source Host           : localhost:3306
     7 Source Database       : springboot
     8 
     9 Target Server Type    : MYSQL
    10 Target Server Version : 50549
    11 File Encoding         : 65001
    12 */
    13 
    14 SET FOREIGN_KEY_CHECKS=0;
    15 
    16 -- ----------------------------
    17 -- Table structure for users
    18 -- ----------------------------
    19 DROP TABLE IF EXISTS `users`;
    20 CREATE TABLE `users` (
    21   `id` int(11) NOT NULL AUTO_INCREMENT,
    22   `name` varchar(10) DEFAULT NULL,
    23   `password` varchar(20) DEFAULT NULL,
    24   `email` varchar(20) DEFAULT NULL,
    25   `birthday` date DEFAULT NULL,
    26   PRIMARY KEY (`id`)
    27 ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
    users.sql
     1 public class Users {
     2     private  Integer id;
     3     private String name;
     4     private String password;
     5     private String email;
     6     private Date birthday;
     7     public Integer getId() {
     8         return id;
     9     }
    10     public void setId(Integer id) {
    11         this.id = id;
    12     }
    13     public String getName() {
    14         return name;
    15     }
    16     public void setName(String name) {
    17         this.name = name;
    18     }
    19     public String getPassword() {
    20         return password;
    21     }
    22     public void setPassword(String password) {
    23         this.password = password;
    24     }
    25     public String getEmail() {
    26         return email;
    27     }
    28     public void setEmail(String email) {
    29         this.email = email;
    30     }
    31     public Date getBirthday() {
    32         return birthday;
    33     }
    34     public void setBirthday(Date birthday) {
    35         this.birthday = birthday;
    36     }
    Users.java

    23.4 在dao层编写一个插入users表的一个方法,并调用到controller层

     1 package com.wu.dao;
     2 
     3 import org.apache.catalina.User;
     4 import org.springframework.beans.factory.annotation.Autowired;
     5 import org.springframework.jdbc.core.JdbcTemplate;
     6 import org.springframework.stereotype.Repository;
     7 
     8 import com.wu.pojo.Users;
     9 
    10 @Repository
    11 public class UsersDao {
    12     @Autowired
    13     public JdbcTemplate jdbcTemplate;//使用jdbc模板
    14     @SuppressWarnings("unused")
    15     public void addUsers(Users users){
    16         jdbcTemplate.update("insert into users(name,password,email,birthday) values(?,?,?,?)",users.getName(),users.getPassword(),users.getEmail(),users.getBirthday());
    17     }
    18 }
    UsersDao.java
     1 package com.wu.service;
     2 
     3 import org.springframework.beans.factory.annotation.Autowired;
     4 import org.springframework.stereotype.Service;
     5 
     6 import com.wu.dao.UsersDao;
     7 import com.wu.pojo.Users;
     8 
     9 @Service
    10 public class UsersService {
    11     @Autowired
    12     private UsersDao usersDao;
    13     public void saveUsers(Users users){
    14         usersDao.addUsers(users);
    15     }
    16 }
    UsersService.java
     1 package com.wu.controller;
     2 
     3 import java.sql.Date;
     4 
     5 import org.springframework.beans.factory.annotation.Autowired;
     6 import org.springframework.web.bind.annotation.RequestMapping;
     7 import org.springframework.web.bind.annotation.RestController;
     8 
     9 import com.wu.pojo.Users;
    10 import com.wu.service.UsersService;
    11 
    12 @RestController
    13 public class UsersController {
    14     @Autowired
    15     private UsersService service;
    16     @RequestMapping("/addUsers")
    17     public String saveUsers(){
    18         Users users=new Users();
    19         users.setBirthday(new java.util.Date());
    20         users.setEmail("xiaoma@wu.com");
    21         users.setName("xiaoma");
    22         users.setPassword("asdf");
    23         service.saveUsers(users);
    24         return "addUsersSuccess";
    25         
    26     }
    27 }
    UsersController.java
     1 package com.wu.app;
     2 
     3 import org.springframework.boot.SpringApplication;
     4 import org.springframework.boot.autoconfigure.SpringBootApplication;
     5 import org.springframework.scheduling.annotation.EnableAsync;
     6 import org.springframework.scheduling.annotation.EnableScheduling;
     7 
     8 
     9 @SpringBootApplication(scanBasePackages={"com.wu.controller","com.wu.service","com.wu.dao"})
    10 public class SpringApplications {
    11         //程序启动入口
    12         public static void main(String []args){
    13             SpringApplication.run(SpringApplications.class, args);
    14         }
    15 }
    启动类

    23.5 总结

    即通过注解注入,无需其他配置,例子比较简单(v_b)

    @Autowired
    public JdbcTemplate jdbcTemplate;//使用jdbc模板

    二十四 SpringBoot整合Mybatis(xml方式)

     24.1 加入相关依赖

     1            <!-- SpringBoot整合mybatis -->
     2        <dependency>
     3                <groupId>org.mybatis.spring.boot</groupId>
     4                <artifactId>mybatis-spring-boot-starter</artifactId>
     5                <version>1.3.1</version>
     6        </dependency>
     7        
     8        <!-- Mysql -->
     9        <dependency>
    10                <groupId>mysql</groupId>
    11                <artifactId>mysql-connector-java</artifactId>
    12        </dependency>
    13        
    14        <!-- druid数据库连接池 -->
    15        <dependency>
    16                <groupId>com.alibaba</groupId>
    17                <artifactId>druid-spring-boot-starter</artifactId>
    18                <version>1.1.0</version>
    19        </dependency>
    20        
    21        <!-- 分页插件 -->
    22        <dependency>
    23                <groupId>com.github.pagehelper</groupId>
    24                <artifactId>pagehelper-spring-boot-starter</artifactId>
    25                <version>1.1.2</version>
    26        </dependency>    
    案例所需的相关依赖

     24.2 相关配置文件

    文件结构:

    1 <?xml version="1.0" encoding="UTF-8"?>
    2 <!DOCTYPE configuration
    3             PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    4             "http://mybatis.org/dtd/mybatis-3-config.dtd">
    5 <configuration>
    6 
    7 </configuration>
    mybatis-config.xml
     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 <mapper namespace="com.wu.mapper.UsersMapper">
     4   <resultMap id="BaseResultMap" type="com.wu.pojo.Users">
     5     <id column="id" jdbcType="INTEGER" property="id" />
     6     <result column="name" jdbcType="VARCHAR" property="name" />
     7     <result column="password" jdbcType="VARCHAR" property="password" />
     8     <result column="email" jdbcType="VARCHAR" property="email" />
     9     <result column="birthday" jdbcType="DATE" property="birthday" />
    10   </resultMap>
    11   <sql id="Base_Column_List">
    12     id, name, password, email, birthday
    13   </sql>
    14   <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    15     select 
    16     <include refid="Base_Column_List" />
    17     from users
    18     where id = #{id,jdbcType=INTEGER}
    19   </select>
    20   <select id="selectAll" resultMap="BaseResultMap">
    21           select
    22            <include refid="Base_Column_List" />
    23            from users 
    24   </select>
    25   <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    26     delete from users
    27     where id = #{id,jdbcType=INTEGER}
    28   </delete>
    29   <insert id="insert" parameterType="com.wu.pojo.Users">
    30     insert into users (id, name, password, 
    31       email, birthday)
    32     values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 
    33       #{email,jdbcType=VARCHAR}, #{birthday,jdbcType=DATE})
    34   </insert>
    35   <insert id="insertSelective" parameterType="com.wu.pojo.Users">
    36     insert into users
    37     <trim prefix="(" suffix=")" suffixOverrides=",">
    38       <if test="id != null">
    39         id,
    40       </if>
    41       <if test="name != null">
    42         name,
    43       </if>
    44       <if test="password != null">
    45         password,
    46       </if>
    47       <if test="email != null">
    48         email,
    49       </if>
    50       <if test="birthday != null">
    51         birthday,
    52       </if>
    53     </trim>
    54     <trim prefix="values (" suffix=")" suffixOverrides=",">
    55       <if test="id != null">
    56         #{id,jdbcType=INTEGER},
    57       </if>
    58       <if test="name != null">
    59         #{name,jdbcType=VARCHAR},
    60       </if>
    61       <if test="password != null">
    62         #{password,jdbcType=VARCHAR},
    63       </if>
    64       <if test="email != null">
    65         #{email,jdbcType=VARCHAR},
    66       </if>
    67       <if test="birthday != null">
    68         #{birthday,jdbcType=DATE},
    69       </if>
    70     </trim>
    71   </insert>
    72   <update id="updateByPrimaryKeySelective" parameterType="com.wu.pojo.Users">
    73     update users
    74     <set>
    75       <if test="name != null">
    76         name = #{name,jdbcType=VARCHAR},
    77       </if>
    78       <if test="password != null">
    79         password = #{password,jdbcType=VARCHAR},
    80       </if>
    81       <if test="email != null">
    82         email = #{email,jdbcType=VARCHAR},
    83       </if>
    84       <if test="birthday != null">
    85         birthday = #{birthday,jdbcType=DATE},
    86       </if>
    87     </set>
    88     where id = #{id,jdbcType=INTEGER}
    89   </update>
    90   <update id="updateByPrimaryKey" parameterType="com.wu.pojo.Users">
    91     update users
    92     set name = #{name,jdbcType=VARCHAR},
    93       password = #{password,jdbcType=VARCHAR},
    94       email = #{email,jdbcType=VARCHAR},
    95       birthday = #{birthday,jdbcType=DATE}
    96     where id = #{id,jdbcType=INTEGER}
    97   </update>
    98 </mapper>
    UsersMapper.xml
     1 package com.wu.mapper;
     2 
     3 import java.util.List;
     4 
     5 import com.wu.pojo.Users;
     6 
     7 public interface UsersMapper {
     8     int deleteByPrimaryKey(Integer id);
     9 
    10     int insert(Users record);
    11 
    12     int insertSelective(Users record);
    13 
    14     Users selectByPrimaryKey(Integer id);
    15 
    16     int updateByPrimaryKeySelective(Users record);
    17 
    18     int updateByPrimaryKey(Users record);
    19     List<Users> selectAll();
    20 }
    UsersMapper.java
     1 spring:
     2   datasource:
     3 #   数据源基本配置
     4     username: root
     5     password: root
     6     driver-class-name: com.mysql.jdbc.Driver
     7     url: jdbc:mysql://localhost:3306/springboot
     8     type: com.alibaba.druid.pool.DruidDataSource
     9 
    10 #    mybatis的配置
    11 mybatis:
    12   mapper-locations: classpath:mapping/UsersMapper.xml
    13   config-location: classpath:mybatis/mybatis-config.xml
    14 
    15 #    分页插件配置
    16 pagehelper:
    17     helperDialect: mysql
    18     reasonable: true
    19     supportMethodsArguments: true
    20     params: count=countSql
    21     returnPageInfo: check
    application.yml
     1 package com.wu.service;
     2 
     3 
     4 
     5 import java.util.List;
     6 
     7 import com.wu.pojo.Users;
     8 
     9 public interface UsersService {
    10     //添加用户
    11     int addUsers(Users users);
    12     //分页查询用户
    13     List<Users> getUserList (int page,int rows);
    14 }
    UsersService.java
     1 package com.wu.service;
     2 
     3 import java.util.List;
     4 
     5 import org.springframework.beans.factory.annotation.Autowired;
     6 import org.springframework.stereotype.Service;
     7 
     8 import com.github.pagehelper.PageHelper;
     9 import com.wu.mapper.UsersMapper;
    10 import com.wu.pojo.Users;
    11 @Service
    12 public class UsersServiceImp implements UsersService {
    13     @Autowired
    14     private UsersMapper mapper;
    15     @Override
    16     public int addUsers(Users users) {
    17         return mapper.insert(users);
    18     }
    19     
    20     @Override
    21     public List<Users> getUserList(int page, int rows) {
    22         PageHelper.startPage(page, rows);
    23         List<Users> usersList = mapper.selectAll();
    24         return usersList;
    25     }
    26     
    27 }
    UsersServiceImp.java
     1 package com.wu.controller;
     2 
     3 import java.util.Date;
     4 import java.util.List;
     5 
     6 import org.springframework.beans.factory.annotation.Autowired;
     7 import org.springframework.web.bind.annotation.PathVariable;
     8 import org.springframework.web.bind.annotation.RequestMapping;
     9 import org.springframework.web.bind.annotation.RestController;
    10 
    11 import com.wu.pojo.Users;
    12 import com.wu.service.UsersService;
    13 
    14 @RestController
    15 public class UsersController {
    16     @Autowired
    17     private UsersService service;
    18     
    19     @RequestMapping("/addUsers")
    20     public String saveUsers(){
    21         Users users=new Users();
    22         users.setBirthday(new Date());
    23         users.setEmail("wm@qq.com");
    24         users.setName("王莽");
    25         users.setPassword("askjdfsl");
    26         service.addUsers(users);
    27         return "success";
    28     }
    29     
    30     @RequestMapping("/getUsers/{page}/{rows}")
    31     public List<Users> getUsers(@PathVariable int page,@PathVariable int rows){
    32         return service.getUserList(page, rows);
    33         
    34     }
    35 }
    UsersController.java
     1 package com.wu.app;
     2 
     3 import org.mybatis.spring.annotation.MapperScan;
     4 import org.springframework.boot.SpringApplication;
     5 import org.springframework.boot.autoconfigure.SpringBootApplication;
     6 import org.springframework.scheduling.annotation.EnableAsync;
     7 import org.springframework.scheduling.annotation.EnableScheduling;
     8 
     9 
    10 @SpringBootApplication(scanBasePackages={"com.wu.controller","com.wu.service"})
    11 @MapperScan("com.wu.mapper")//需要单独扫描
    12 public class SpringApplications {
    13         //程序启动入口
    14         public static void main(String []args){
    15             SpringApplication.run(SpringApplications.class, args);
    16         }
    17 }
    启动类

    24.3 结果

    二十五 SpringBoot整合Mybatis(注解方式)

    25.0  补充知识:MyBatis 中 @Param 注解的四种使用场景

     25.1 相关依赖

     1 <!-- SpringBoot整合mybatis(注解方式) -->
     2        <dependency>
     3                <groupId>org.mybatis.spring.boot</groupId>
     4                <artifactId>mybatis-spring-boot-starter</artifactId>
     5                <version>1.3.1</version>
     6        </dependency>
     7        
     8        <!-- Mysql -->
     9        <dependency>
    10                <groupId>mysql</groupId>
    11                <artifactId>mysql-connector-java</artifactId>
    12        </dependency>
    mybatis和mysql的依赖

    25.2 配置application.yml

    1 spring:
    2   datasource:
    3 #   数据源基本配置
    4     username: root
    5     password:  root
    6     driver-class-name: com.mysql.jdbc.Driver
    7     url: jdbc:mysql://localhost:3306/springboot
    application.yml

    25.3 文件结构

     

    与xml方式相比,注解方式不用再配置相关的mybatis  xml文件,只需要配置相关接口,如下:

     1 package com.wu.mapper;
     2 
     3 import java.util.List;
     4 
     5 import org.apache.ibatis.annotations.Param;
     6 import org.apache.ibatis.annotations.Select;
     7 
     8 import com.wu.pojo.Users;
     9 import org.apache.ibatis.annotations.Select;
    10 public interface UsersMapper {
    11         @Select("select * from users where name=#{name}")
    12         Users selectByName(@Param(value = "name") String name);
    13 }
    接口:UsersMapper.java

    25.4 结果

    25.5 总结

    注解方式直接在相关实体类的接口上通过相关的注解,在注解里面写上sql语句

     二十六 SpringBoot区分多数据源

    参考文档1文档2

    26.0  方式一:分包; 方式二:注解(可以参考以上文档)

    26.1  分包方式实现

      26.1.0 样例结构如下

      26.1.1 添加相关依赖(默认都已经添加了 web的依赖)

     1  <dependencies>
     2     <dependency>
     3         <groupId>org.springframework</groupId>
     4         <artifactId>springloaded</artifactId>
     5     </dependency>
     6     <dependency>
     7         <groupId>org.springframework.boot</groupId>
     8         <artifactId>spring-boot-devtools</artifactId>
     9     </dependency>
    10        <dependency>
    11           <groupId>org.springframework.boot</groupId>
    12           <artifactId>spring-boot-starter-web</artifactId>  
    13        </dependency>
    14   
    15   <!-- mybatis -->
    16        <dependency>
    17                <groupId>org.mybatis.spring.boot</groupId>
    18                <artifactId>mybatis-spring-boot-starter</artifactId>
    19                <version>1.3.1</version>
    20        </dependency>
    21        
    22        <!-- Mysql -->
    23        <dependency>
    24                <groupId>mysql</groupId>
    25                <artifactId>mysql-connector-java</artifactId>
    26        </dependency>
    27    </dependencies>
    相关依赖

      26.1.2  创建两个数据库,并分别建一个user表(表名不同)

    省略

      26.1.3 在全局配置文件application.properties中配置多数据源

     1 #数据源1,db1,db2都是数据库名
     2 spring.datasource.db1.driver-class-name=com.mysql.jdbc.Driver
     3 spring.datasource.db1.username=root
     4 spring.datasource.db1.password=123456
     5 spring.datasource.db1.url=jdbc:mysql://localhost:3306/db1
     6 
     7 #数据源2
     8 spring.datasource.db2.driver-class-name=com.mysql.jdbc.Driver
     9 spring.datasource.db2.username=root
    10 spring.datasource.db2.password=123456
    11 spring.datasource.db2.url=jdbc:mysql://localhost:3306/db2
    在application.properties中配置两个数据源

      26.1.4 分别配置两个数据源加载到spring容器中

     1 package com.wu.datasource;
     2 
     3 import javax.sql.DataSource;
     4 
     5 import org.apache.ibatis.session.SqlSessionFactory;
     6 import org.mybatis.spring.SqlSessionFactoryBean;
     7 import org.mybatis.spring.SqlSessionTemplate;
     8 import org.mybatis.spring.annotation.MapperScan;
     9 import org.springframework.beans.factory.annotation.Qualifier;
    10 import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
    11 import org.springframework.boot.context.properties.ConfigurationProperties;
    12 import org.springframework.context.annotation.Bean;
    13 import org.springframework.context.annotation.Configuration;
    14 import org.springframework.context.annotation.Primary;
    15 import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    16 
    17 @Configuration//表明这是一个配置类
    18 @MapperScan(basePackages="com.wu.db1.mapper",sqlSessionFactoryRef = "db1SqlSessionFactory")//扫描用到该数据源的mapper所在的包
    19 public class DataSource1 {
    20     /*
    21      * 配置DataSource
    22      */    
    23     @Bean(name="db1DataSource")//将该对象放入Spring容器中
    24     @Primary// 表示这个数据源是默认数据源
    25     @ConfigurationProperties(prefix = "spring.datasource.db1")// prefix表示全局配置文件中的前缀
    26      public DataSource getDateSource1() {
    27         return DataSourceBuilder.create().build();
    28     }
    29     
    30     /*
    31      * 配置SqlSessionFactory
    32      */
    33     @Bean(name="db1SqlSessionFactory")
    34     @Primary
    35     //@Qualifier表示查找Spring容器中名字为db1DataSource的对象
    36     public SqlSessionFactory getSqlSessionFactory1(@Qualifier("db1DataSource") DataSource datasource)
    37             throws Exception {
    38         SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    39         bean.setDataSource(datasource);
    40         return bean.getObject();
    41     }
    42     
    43     /*
    44      * 配置事务管理器
    45      */
    46     @Bean(name="db1TransactionManager")
    47     @Primary
    48     public DataSourceTransactionManager getTransactionManager1(@Qualifier("db1DataSource") DataSource datasource){
    49         return new DataSourceTransactionManager(datasource);
    50     }
    51     
    52     /*
    53      * 配置Sqlsessiontemplate
    54      */
    55     @Bean(name="db1SqlSessionTemplate")
    56     @Primary
    57     public SqlSessionTemplate getSqlSessionTemplate1( @Qualifier("db1SqlSessionFactory") SqlSessionFactory sessionfactory){
    58         return new SqlSessionTemplate(sessionfactory);
    59     }
    60     
    61     
    62 }
    DataSource1.java,这是默认数据源
     1 package com.wu.datasource;
     2 
     3 import javax.sql.DataSource;
     4 
     5 import org.apache.ibatis.session.SqlSessionFactory;
     6 import org.mybatis.spring.SqlSessionFactoryBean;
     7 import org.mybatis.spring.SqlSessionTemplate;
     8 import org.mybatis.spring.annotation.MapperScan;
     9 import org.springframework.beans.factory.annotation.Qualifier;
    10 import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
    11 import org.springframework.boot.context.properties.ConfigurationProperties;
    12 import org.springframework.context.annotation.Bean;
    13 import org.springframework.context.annotation.Configuration;
    14 import org.springframework.context.annotation.Primary;
    15 import org.springframework.jdbc.datasource.DataSourceTransactionManager;
    16 
    17 @Configuration//表明这是一个配置类
    18 @MapperScan(basePackages="com.wu.db2.mapper",sqlSessionFactoryRef = "db2SqlSessionFactory")//扫描用到该数据源的mapper所在的包
    19 public class DataSource2 {
    20     /*
    21      * 配置DataSource
    22      */    
    23     @Bean(name="db2DataSource")//将该对象放入Spring容器中
    24     @ConfigurationProperties(prefix = "spring.datasource.db2")// prefix表示全局配置文件中的前缀
    25      public DataSource getDateSource2() {
    26         return DataSourceBuilder.create().build();
    27     }
    28     
    29     /*
    30      * 配置SqlSessionFactory
    31      */
    32     @Bean(name="db2SqlSessionFactory")
    33     //@Qualifier表示查找Spring容器中名字为db2DataSource的对象
    34     public SqlSessionFactory getSqlSessionFactory2(@Qualifier("db2DataSource") DataSource datasource)
    35             throws Exception {
    36         SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
    37         bean.setDataSource(datasource);
    38         return bean.getObject();
    39     }
    40     
    41     /*
    42      * 配置事务管理器
    43      */
    44     @Bean(name="db2TransactionManager")
    45     public DataSourceTransactionManager getTransactionManager2(@Qualifier("db2DataSource") DataSource datasource){
    46         return new DataSourceTransactionManager(datasource);
    47     }
    48     
    49     /*
    50      * 配置Sqlsessiontemplate
    51      */
    52     @Bean(name="db2SqlSessionTemplate")
    53     public SqlSessionTemplate getSqlSessionTemplate2( @Qualifier("db2SqlSessionFactory") SqlSessionFactory sessionfactory){
    54         return new SqlSessionTemplate(sessionfactory);
    55     }
    56     
    57     
    58 }
    DataSource2.java

      26.1.5 相应的mapper接口

    1 package com.wu.db1.mapper;
    2 
    3 import org.apache.ibatis.annotations.Insert;
    4 import org.apache.ibatis.annotations.Param;
    5 
    6 public interface User1Mapper {
    7     @Insert("insert into user1(name,password) values(#{name},#{password})")
    8     void addUser1(@Param("name")String name,@Param("password")String password);
    9 }
    User1Mapper.java
     1 package com.wu.db2.mapper;
     2 
     3 import org.apache.ibatis.annotations.Insert;
     4 import org.apache.ibatis.annotations.Param;
     5 import org.springframework.beans.factory.annotation.Qualifier;
     6 @Qualifier("db2SqlSessionFactory")//查找相应的session工厂,去掉也行
     7 public interface User2Mapper {
     8     @Insert("insert into user2(name,password) values(#{name},#{password})")
     9     void addUser2(@Param("name")String name,@Param("password")String password);
    10 }
    User2Mapper.java

      26.1.6 其他层的编写如下

    1 package com.wu.db1.service;
    2 
    3 import com.wu.pojo.User1;
    4 
    5 public interface User1Service {
    6     void addUser1(User1 user1);
    7 }
    User1Service.java
     1 package com.wu.db1.service;
     2 
     3 import org.springframework.beans.factory.annotation.Autowired;
     4 import org.springframework.stereotype.Service;
     5 
     6 import com.wu.db1.mapper.User1Mapper;
     7 import com.wu.pojo.User1;
     8 
     9 @Service
    10 public class User1ServiceImp implements User1Service {
    11     @Autowired
    12     private User1Mapper mapper;
    13 
    14     @Override
    15     public void addUser1(User1 user1) {
    16         mapper.addUser1(user1.getName(),user1.getPassword());
    17     }
    18     
    19     
    20 }
    User1ServiceImp.java
     1 package com.wu.controller;
     2 
     3 import org.springframework.beans.factory.annotation.Autowired;
     4 import org.springframework.web.bind.annotation.RequestMapping;
     5 import org.springframework.web.bind.annotation.RestController;
     6 
     7 import com.wu.db1.service.User1Service;
     8 import com.wu.db2.service.User2Service;
     9 import com.wu.pojo.User1;
    10 import com.wu.pojo.User2;
    11 
    12 @RestController
    13 public class UserController {
    14     @Autowired
    15     private User1Service service1;
    16     @Autowired
    17     private User2Service service2;
    18     
    19     @RequestMapping("/addUser")
    20     public String addUser(){
    21         User1 user1=new User1();
    22         user1.setName("1111");
    23         user1.setPassword("111");
    24         
    25         User2 user2=new User2();
    26         user2.setName("222");
    27         user2.setPassword("222");
    28         
    29         service2.addUser2(user2);
    30         service1.addUser1(user1);
    31         return "success";
    32     }
    33 }
    UserController.java

    二十七 SpringBoot的事务管理

    什么是事务,spring和springboot中的事务管理,可以参考以下文章

    27.0 参考文章1   文章2    文章3

    27.1 前言

    在SpringBoot中推荐使用@Transactional 注解声明事务,当我们使用了spring-boot-starter-jdbcspring-boot-starter-data-jpa依赖的时候,框架会自动默认分别注入DataSourceTransactionManagerJpaTransactionManager。所以我们不需要任何额外 配置就可以用@Transactional注解进行事务的使用。

    二十八 SpringBoot整合JPA-Hibernate

    个人所想:这个不知用的多不多?

    28.0 相关知识: JPA和Hibernate的关系    Hibernate入门   

    28.1  相关依赖

    1            <!-- SpringBoot整合JPA-->
    2        <dependency>
    3                <groupId>org.springframework.boot</groupId>
    4                <artifactId>spring-boot-starter-data-jpa</artifactId>
    5        </dependency>
    6        <dependency>
    7                <groupId>mysql</groupId>
    8                <artifactId>mysql-connector-java</artifactId>
    9        </dependency>    
    其他如web依赖已经添加,这是JPA和mysql

    28.2 在application.properties中的相关配置

     1 #数据库配置
     2 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
     3 spring.datasource.username=root
     4 spring.datasource.password=123456
     5 spring.datasource.url=jdbc:mysql://localhost:3306/springboot
     6 
     7 #让控制器输出json字符串格式以及hibernate的相关配置
     8 spring.jackson.serialization.indent-output=true
     9 spring.jpa.hibernate.ddl-auto=update
    10 spring.jpa.show-sql=true
    11 spring.jpa.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
    application.properties

    28.3 编写实体类

     1 package com.wu.pojo;
     2 
     3 import java.util.Date;
     4 
     5 import javax.persistence.Column;
     6 import javax.persistence.Entity;
     7 import javax.persistence.GeneratedValue;
     8 import javax.persistence.GenerationType;
     9 import javax.persistence.Id;
    10 import javax.persistence.Table;
    11 @Entity//自动配置该实体类
    12 @Table(name="t_user")//指定表明,不指定则和类名相同
    13 public class User {
    14         @Id//指定主键
    15         @GeneratedValue(strategy=GenerationType.IDENTITY)//主键生成策略
    16          private Integer id;
    17         
    18         @Column//可以通过该注解自定义列名
    19         private String name;
    20 
    21         private String password;
    22 
    23         private String email;
    24 
    25         private Date birthday;
    26 
    27         public Integer getId() {
    28             return id;
    29         }
    30 
    31         public void setId(Integer id) {
    32             this.id = id;
    33         }
    34 
    35         public String getName() {
    36             return name;
    37         }
    38 
    39         public void setName(String name) {
    40             this.name = name == null ? null : name.trim();
    41         }
    42 
    43         public String getPassword() {
    44             return password;
    45         }
    46 
    47         public void setPassword(String password) {
    48             this.password = password == null ? null : password.trim();
    49         }
    50 
    51         public String getEmail() {
    52             return email;
    53         }
    54 
    55         public void setEmail(String email) {
    56             this.email = email == null ? null : email.trim();
    57         }
    58 
    59         public Date getBirthday() {
    60             return birthday;
    61         }
    62 
    63         public void setBirthday(Date birthday) {
    64             this.birthday = birthday;
    65         }
    66 }
    User.java

    28.4 dao层

    1 package com.wu.dao;
    2 
    3 import org.springframework.data.jpa.repository.JpaRepository;
    4 
    5 import com.wu.pojo.User;
    6 //需要继承 extends JpaRepository 其中的属性分别时实体类的类型和主键的类型
    7 public interface UserDao extends JpaRepository<User,Integer>{
    8     
    9 }
    UserDao.java

    28.5 service层

    1 package com.wu.service;
    2 
    3 import com.wu.pojo.User;
    4 
    5 public interface UserService {
    6     void addUser(User user);
    7 }
    UserService.java
     1 package com.wu.service;
     2 
     3 import org.springframework.beans.factory.annotation.Autowired;
     4 import org.springframework.stereotype.Service;
     5 
     6 import com.wu.dao.UserDao;
     7 import com.wu.pojo.User;
     8 @Service
     9 public class UserServiceImp implements UserService {
    10     @Autowired
    11     private UserDao dao;
    12     
    13     @Override
    14     public void addUser(User user) {
    15         //可以直接通过该dao接口实现CRUD
    16         dao.save(user);
    17     }
    18     
    19 }
    UserServiceImp.java

    28.6 controller层

     1 package com.wu.controller;
     2 
     3 import java.util.Date;
     4 
     5 import org.springframework.beans.factory.annotation.Autowired;
     6 import org.springframework.web.bind.annotation.RequestMapping;
     7 import org.springframework.web.bind.annotation.RestController;
     8 
     9 import com.wu.pojo.User;
    10 import com.wu.service.UserService;
    11 
    12 @RestController
    13 public class UserController {
    14     @Autowired
    15     private UserService service;
    16     
    17     @RequestMapping("/addUser")
    18     public String addUser(){
    19         User user=new User();
    20         user.setBirthday(new Date());
    21         user.setEmail("wm@wu.com");
    22         user.setName("二小");
    23         user.setPassword("aslkfjls");
    24         service.addUser(user);
    25         return "success";
    26     }
    27 }
    UserController.java

    28.7 启动类

     1 package com.wu.app;
     2 
     3 import org.springframework.boot.SpringApplication;
     4 import org.springframework.boot.autoconfigure.SpringBootApplication;
     5 import org.springframework.boot.autoconfigure.domain.EntityScan;
     6 import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
     7 
     8 @SpringBootApplication(scanBasePackages={"com.wu"})
     9 @EntityScan("com.wu.pojo")//扫描实体包
    10 @EnableJpaRepositories("com.wu.dao")//扫描dao层
    11 public class SpringApplications {
    12         //程序启动入口
    13         public static void main(String []args){
    14             SpringApplication.run(SpringApplications.class, args);
    15         }
    16 }
    启动类中需要注意扫描实体和dao所在的包
    作者:wuba
    出处:http://www.cnblogs.com/wuba/
    版权声明:本博客所有文章除特别声明外,均采用CC BY-NC-SA 4.0许可协议。转载请注明出处!
  • 相关阅读:
    Java环境变量的简记
    win10系统安装postgresql后无法连接
    VB.net Postgresql调用,NpgsqlDataReader,NpgsqlDataAdapter的调用例子。
    Postgresql服务器无法连接(10060错误信息)
    解决visual studio的No EditorOptionDefinition 错误
    从零开始Wordpress建站经验分享,内附耗时及成本
    Servlet端 接收不到4096,8192长度的JSON参数
    Wiser的Junit测试用法
    Oracle表生成JavaBean
    mysql表生成JavaBean
  • 原文地址:https://www.cnblogs.com/wuba/p/11232002.html
Copyright © 2020-2023  润新知