springboot整合持久层
1. springboot整合jdbcTemplate
1.1 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>jdbctemplate</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jdbctemplate</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
1.2 application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/demo?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
1.3 model
package com.yl.jdbctemplate.model;
import java.io.Serializable;
public class Student implements Serializable {
private Integer id;
private String stuName;
private String stuNo;
private Integer age;
private String stuMessage;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", stuName='" + stuName + '\'' +
", stuNo='" + stuNo + '\'' +
", age=" + age +
", stuMessage='" + stuMessage + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getStuMessage() {
return stuMessage;
}
public void setStuMessage(String stuMessage) {
this.stuMessage = stuMessage;
}
}
1.4 service
package com.yl.jdbctemplate.service;
import com.yl.jdbctemplate.model.Student;
import java.util.List;
public interface StudentService {
int addStudent(Student student);
int addStudent2(Student student);
int updateStudent(Student student);
int deleteStudentById(Integer id);
List<Student> getAllStudent();
List<Student> getAllStudent2();
}
1.5 serviceImpl,crud案例
package com.yl.jdbctemplate.service.impl;
import com.yl.jdbctemplate.model.Student;
import com.yl.jdbctemplate.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Service;
import java.sql.*;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public int addStudent(Student student) {
int result = jdbcTemplate.update("insert into student(stu_name,stu_no,age,stu_message) values(?,?,?,?) "
,student.getStuName(),student.getStuNo(),student.getAge(),student.getStuMessage());
return result;
}
//插入数据,并且回写id
@Override
public int addStudent2(Student student) {
GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
int result = jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
//插入数据后返回主键
PreparedStatement ps = con.prepareStatement("insert into student(stu_name,stu_no,age,stu_message) values(?,?,?,?)"
, Statement.RETURN_GENERATED_KEYS);
ps.setString(1,student.getStuName());
ps.setString(2,student.getStuNo());
ps.setInt(3,student.getAge());
ps.setString(4,student.getStuMessage());
return ps;
}
},keyHolder);
student.setId(keyHolder.getKey().intValue());
return result;
}
@Override
public int updateStudent(Student student) {
int result = jdbcTemplate.update("update student set stu_name=?,stu_no=?,age=?,stu_message=? where id = ?",
student.getStuName(),student.getStuNo(),student.getAge(),student.getStuMessage(),student.getId());
return result;
}
@Override
public int deleteStudentById(Integer id) {
int result = jdbcTemplate.update("delete from student where id = ?", id);
return result;
}
//这种查询比较麻烦,要一个一个设值
@Override
public List<Student> getAllStudent() {
List<Student> list = jdbcTemplate.query("select * from student", new RowMapper<Student>() {
@Override
public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
int id = rs.getInt("id");
String stuName = rs.getString("stu_name");
String stuNo = rs.getString("stu_no");
int age = rs.getInt("age");
String stuMessage = rs.getString("stu_message");
Student student = new Student();
student.setId(id);
student.setStuName(stuName);
student.setStuNo(stuNo);
student.setAge(age);
student.setStuMessage(stuMessage);
return student;
}
});
return list;
}
//这种方式比较方便,但是有一个前提:数据库表的字段和java实体类的属性名要完全一致
//或者数据库表的字段下划线命名方式对应java实体类属性名的驼峰命名方式
@Override
public List<Student> getAllStudent2() {
List<Student> list = jdbcTemplate.query("select * from student",new BeanPropertyRowMapper<>(Student.class));
return list;
}
}
2. jdbcTemplate配置多数据源
2.1 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>jdbctemplateutil</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jdbctemplateutil</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.2 application.properties
# springboot配置多数据源
spring.datasource.one.username=root
spring.datasource.one.password=root
spring.datasource.one.jdbcurl=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.two.username=root
spring.datasource.two.password=root
spring.datasource.two.jdbcurl=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
2.3 实体类
package com.yl.jdbctemplateutil.model;
import java.io.Serializable;
public class Student implements Serializable {
private Integer id;
private String stuName;
private String stuNo;
private Integer age;
private String stuMessage;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", stuName='" + stuName + '\'' +
", stuNo='" + stuNo + '\'' +
", age=" + age +
", stuMessage='" + stuMessage + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getStuMessage() {
return stuMessage;
}
public void setStuMessage(String stuMessage) {
this.stuMessage = stuMessage;
}
}
2.4 数据源配置
package com.yl.jdbctemplateutil.config;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DatasourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.one")
DataSource dsOne() {
return new HikariDataSource();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.two")
DataSource dsTwo() {
return new HikariDataSource();
}
}
2.5 jdbctemplate配置
package com.yl.jdbctemplateutil.config;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
@Configuration
public class JdbcTemplateConfig {
@Bean
JdbcTemplate jdbcTemplateOne(@Qualifier("dsOne")DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean
JdbcTemplate jdbcTemplateTwo(@Qualifier("dsTwo")DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
2.6 注入模板测试
3. springboot整合mybatis(注解方式)
3.1 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3.2 application.properties
# 数据源配置
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
3.3 实体类
package com.yl.mybatis.model;
import java.io.Serializable;
public class Student implements Serializable {
private Integer id;
private String stuName;
private String stuNo;
private Integer age;
private String stuMessage;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", stuName='" + stuName + '\'' +
", stuNo='" + stuNo + '\'' +
", age=" + age +
", stuMessage='" + stuMessage + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getStuMessage() {
return stuMessage;
}
public void setStuMessage(String stuMessage) {
this.stuMessage = stuMessage;
}
}
3.4 mapper
package com.yl.mybatis.mapper;
import com.yl.mybatis.model.Student;
import org.apache.ibatis.annotations.*;
import java.util.List;
public interface StudentMapper {
@Select("select * from student where id = #{id}")
Student getStudentById(Integer id);
@Insert("insert into student(stu_name,stu_no,age,stu_message) values(#{stuName},#{stuNo},#{age},#{stuMessage})")
//回写id
@SelectKey(statement = "select last_insert_id()",keyProperty = "id",before = false,resultType = Integer.class)
Integer addStudent(Student student);
//表字段和java实体属性映射
@Results({
@Result(property = "stuName",column = "stu_name"),
@Result(property = "stuNo",column = "stu_no"),
@Result(property = "stuMessage",column = "stu_message")
})
@Select("select * from student")
List<Student> getAllStudent();
@Delete("delete from student where id = #{id}")
Integer deleteById(Integer id);
@Update("update student set stu_name = #{stuName},stu_no = #{stuNo},age = #{age},stu_message = #{stuMessage} where id = #{id}")
Integer updateByStudent(Student student);
}
3.5 service
package com.yl.mybatis.service;
import com.yl.mybatis.model.Student;
import java.util.List;
public interface StudentService {
Student getStudentById(Integer id);
Integer addStudent(Student student);
List<Student> getAllStudent();
Integer deleteById(Integer id);
Integer updateById(Student student);
}
3.6 srviceImpl
package com.yl.mybatis.service.impl;
import com.yl.mybatis.mapper.StudentMapper;
import com.yl.mybatis.model.Student;
import com.yl.mybatis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student getStudentById(Integer id) {
return studentMapper.getStudentById(id);
}
@Override
public Integer addStudent(Student student) {
return studentMapper.addStudent(student);
}
@Override
public List<Student> getAllStudent() {
return studentMapper.getAllStudent();
}
@Override
public Integer deleteById(Integer id) {
return studentMapper.deleteById(id);
}
@Override
public Integer updateById(Student student) {
return studentMapper.updateByStudent(student);
}
}
3.7 扫描mapper
3.8 测试
4. springboot整合mybatis(xml方式)
4.1 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
4.2 application.xml
# 数据源配置
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
# mybatis配置
# 扫描xml文件
mybatis.mapper-locations=classpath:mapper/*.xml
4.3 实体类
package com.yl.mybatis.model;
import java.io.Serializable;
public class Student implements Serializable {
private Integer id;
private String stuName;
private String stuNo;
private Integer age;
private String stuMessage;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", stuName='" + stuName + '\'' +
", stuNo='" + stuNo + '\'' +
", age=" + age +
", stuMessage='" + stuMessage + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getStuMessage() {
return stuMessage;
}
public void setStuMessage(String stuMessage) {
this.stuMessage = stuMessage;
}
}
4.4 mapper
package com.yl.mybatis.mapper;
import com.yl.mybatis.model.Student;
import java.util.List;
public interface StudentMapper {
Student getStudentById(Integer id);
Integer addStudent(Student student);
List<Student> getAllStudent();
Integer deleteById(Integer id);
Integer updateById(Student student);
}
4.5 mapper.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">
<mapper namespace="com.yl.mybatis.mapper.StudentMapper">
<resultMap id="BaseResultMap" type="com.yl.mybatis.model.Student">
<id property="id" column="id"/>
<result property="stuName" column="stu_name"/>
<result property="stuNo" column="stu_no"/>
<result property="age" column="age"/>
<result property="stuMessage" column="stu_message"/>
</resultMap>
<select id="getStudentById" resultMap="BaseResultMap">
select * from student where id = #{id}
</select>
<select id="getAllStudent" resultMap="BaseResultMap">
select * from student
</select>
<!--回写id-->
<insert id="addStudent" useGeneratedKeys="true" keyProperty="id">
insert into student(stu_name,stu_no,age,stu_message) values(#{stuName},#{stuNo},#{age},#{stuMessage})
</insert>
<delete id="deleteById" parameterType="java.lang.Integer">
delete from student where id = #{id}
</delete>
<update id="updateById" parameterType="com.yl.mybatis.model.Student">
update student set stu_name=#{stuName},stu_no=#{stuNo},age=#{age},stu_message=#{stuMessage} where id = #{id}
</update>
</mapper>
4.6 service
package com.yl.mybatis.service;
import com.yl.mybatis.model.Student;
import java.util.List;
public interface StudentService {
Student getStudentById(Integer id);
Integer addStudent(Student student);
List<Student> getAllStudent();
Integer deleteById(Integer id);
Integer updateById(Student student);
}
4.7 serviceImpl
package com.yl.mybatis.service.impl;
import com.yl.mybatis.mapper.StudentMapper;
import com.yl.mybatis.model.Student;
import com.yl.mybatis.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentMapper studentMapper;
@Override
public Student getStudentById(Integer id) {
return studentMapper.getStudentById(id);
}
@Override
public Integer addStudent(Student student) {
return studentMapper.addStudent(student);
}
@Override
public List<Student> getAllStudent() {
return studentMapper.getAllStudent();
}
@Override
public Integer deleteById(Integer id) {
return studentMapper.deleteById(id);
}
@Override
public Integer updateById(Student student) {
return studentMapper.updateById(student);
}
}
4.7 扫描mapper
5. mybatis整合多数据源
5.1 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>mybatisutil</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>mybatisutil</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
5.2 application.properties
# 数据源配置
spring.datasource.one.username=root
spring.datasource.one.password=root
spring.datasource.one.jdbcurl=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
spring.datasource.two.username=root
spring.datasource.two.password=root
spring.datasource.two.jdbcurl=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
5.3 实体类
package com.yl.mybatisutil.model;
import java.io.Serializable;
public class Student implements Serializable {
private Integer id;
private String stuName;
private String stuNo;
private Integer age;
private String stuMessage;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", stuName='" + stuName + '\'' +
", stuNo='" + stuNo + '\'' +
", age=" + age +
", stuMessage='" + stuMessage + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public String getStuNo() {
return stuNo;
}
public void setStuNo(String stuNo) {
this.stuNo = stuNo;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getStuMessage() {
return stuMessage;
}
public void setStuMessage(String stuMessage) {
this.stuMessage = stuMessage;
}
}
5.4 mapper1
package com.yl.mybatisutil.mapper1;
import com.yl.mybatisutil.model.Student;
import java.util.List;
public interface StudentMapper1 {
List<Student> getAllStudent();
}
5.5 mapper2
package com.yl.mybatisutil.mapper2;
import com.yl.mybatisutil.model.Student;
import java.util.List;
public interface StudentMapper2 {
List<Student> getAllStudent();
}
5.6 mapper1.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">
<mapper namespace="com.yl.mybatisutil.mapper1.StudentMapper1">
<select id="getAllStudent" resultType="com.yl.mybatisutil.model.Student">
select * from student
</select>
</mapper>
5.7 mapper2.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">
<mapper namespace="com.yl.mybatisutil.mapper2.StudentMapper2">
<select id="getAllStudent" resultType="com.yl.mybatisutil.model.Student">
select * from student
</select>
</mapper>
5.8 数据源配置
package com.yl.mybatisutil.config;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* 多数据源配置
*/
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.one")
DataSource dsOne() {
return new HikariDataSource();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.two")
DataSource dsTwo() {
return new HikariDataSource();
}
}
5.9 mybatis配置1
package com.yl.mybatisutil.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* mybatis的配置
*/
@Configuration
@MapperScan(basePackages = "com.yl.mybatisutil.mapper1",sqlSessionFactoryRef = "sqlSessionFactory1",sqlSessionTemplateRef = "sqlSessionTemplate1")
public class MyBatisConfigOne {
@Qualifier("dsOne")
@Autowired
DataSource dataSource;
@Bean
SqlSessionFactory sqlSessionFactory1() {
try {
SqlSessionFactory sqlSessionFactory = null;
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactory = sqlSessionFactoryBean.getObject();
return sqlSessionFactory;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Bean
SqlSessionTemplate sqlSessionTemplate1() {
return new SqlSessionTemplate(sqlSessionFactory1());
}
}
5.10 mybatis配置2
package com.yl.mybatisutil.config;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
/**
* mybatis的配置
*/
@Configuration
@MapperScan(basePackages = "com.yl.mybatisutil.mapper2",sqlSessionFactoryRef = "sqlSessionFactory2",sqlSessionTemplateRef = "sqlSessionTemplate2")
public class MyBatisConfigTwo {
@Qualifier("dsTwo")
@Autowired
DataSource dataSource;
@Bean
SqlSessionFactory sqlSessionFactory2() {
try {
SqlSessionFactory sqlSessionFactory = null;
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactory = sqlSessionFactoryBean.getObject();
return sqlSessionFactory;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Bean
SqlSessionTemplate sqlSessionTemplate2() {
return new SqlSessionTemplate(sqlSessionFactory2());
}
}
5.11 项目结构
6. springboot动态切换数据源
6.1 先搭建好mysql主从同步环境
参考这里链接: https://blog.csdn.net/weixin_41359273/article/details/120556396.
6.2 项目结构
6.3 pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>dynamicdata</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>dynamicdata</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<!--配置动态数据源所需依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>3.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
6.4 application.yaml
如下ip地址为虚拟机地址
spring:
datasource:
dynamic:
#默认就是master可以不指定
primary: master
strict: false
datasource:
master:
url: jdbc:mysql://192.168.244.129:33061/demo1?characterEncoding=UTF-8&useUnicode=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
salve:
url: jdbc:mysql://192.168.244.129:33062/demo1?characterEncoding=UTF-8&useUnicode=true
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
6.5 model
package com.yl.dynamicdata.model;
public class User {
private Integer id;
private String userName;
private String password;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
}
6.6 service
package com.yl.dynamicdata.service;
import com.yl.dynamicdata.model.User;
import java.util.List;
public interface UserService {
Integer addUser(User user);
List<User> getAllUsers();
}
6.7 service.impl,推荐@DS注解使用在service层
package com.yl.dynamicdata.service.impl;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.yl.dynamicdata.mapper.UserMapper;
import com.yl.dynamicdata.model.User;
import com.yl.dynamicdata.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
//指定使用主机
@DS("master")
@Override
public Integer addUser(User user) {
return userMapper.addUser(user);
}
//指定使用从机
@DS("slave")
@Override
public List<User> getAllUsers() {
return userMapper.getAllUsers();
}
}
6.8 mapper
package com.yl.dynamicdata.mapper;
import com.yl.dynamicdata.model.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
Integer addUser(User user);
List<User> getAllUsers();
}
6.9 mapper.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">
<mapper namespace="com.yl.dynamicdata.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.yl.dynamicdata.model.User">
<id property="id" column="id"/>
<result property="userName" column="user_name"/>
<result property="password" column="password"/>
</resultMap>
<insert id="addUser">
insert into user(user_name,password) values(#{userName},#{password});
</insert>
<select id="getAllUsers" resultMap="BaseResultMap">
select * from user;
</select>
</mapper>
6.9 主程序上扫描mapper
6.10 测试
7. springboot整合spring data jpa
7. 1 springboot整合spring data jpa实现单表crud
1)pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jpa</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.19</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2)application.properties
# 数据库配置
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://192.168.244.129:33061/demo1?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
# jpa的配置
spring.jpa.database=mysql
# 是否显示在控制台打印sql
spring.jpa.show-sql=true
# 使用哪个平台
spring.jpa.database-platform=mysql
# 修改实体类,数据的表是否也是跟着更新
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
3)model
package com.yl.jpa.model;
import javax.persistence.*;
import java.util.Date;
//指定数据库哪一个表
@Entity(name = "t_book")
public class Book {
//标明主键以及生成策略
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//和数据表的字段作映射,可以设置长度,非空,唯一等属性
@Column(name = "name", nullable = false,unique = true,length = 100)
private String name;
@Column(name = "author")
private String author;
@Column(name = "publishDate")
private Date publishDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getPublishDate() {
return publishDate;
}
public void setPublishDate(Date publishDate) {
this.publishDate = publishDate;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", author='" + author + '\'' +
", publishDate=" + publishDate +
'}';
}
}
4)dao
package com.yl.jpa.dao;
import com.yl.jpa.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BookDao extends JpaRepository<Book,Long> {
}
5)测试
5.1)新增和修改数据,共用save方法,实体有id则为修改,没有id则为新增
@Test
void contextLoads() {
Book book = new Book();
book.setName("三国演义");
book.setAuthor("罗贯中");
book.setPublishDate(new Date());
bookDao.save(book);
}
5.2 )根据id查询实体
@Test
void test() {
Optional<Book> book = bookDao.findById(1L);
System.out.println(book);
}
5.3 )查询所有数据
@Test
void test1() {
List<Book> books = bookDao.findAll();
System.out.println(books);
}
5.4 )分页查询
@Test
void test3() {
//页码从0开始,0代表第一页
PageRequest pageRequest = PageRequest.of(1,3, Sort.by(Sort.Order.desc("id")));
Page<Book> books = bookDao.findAll(pageRequest);
//总记录数
System.out.println(books.getTotalElements());
//总页数
int totalPages = books.getTotalPages();
//查询到的数据
System.out.println(books.getContent());
//每页的记录数
System.out.println(books.getSize());
//是否有下一页
System.out.println(books.hasNext());
//是否有上一页
System.out.println(books.hasPrevious());
//是否为最后一页
System.out.println(books.isLast());
//是否为第一页
System.out.println(books.isFirst());
//当前页码
System.out.println(books.getNumber());
//当前页的记录数
System.out.println(books.getNumberOfElements());
}
5.5 )删除
@Test
void test2() {
bookDao.deleteById(2L);
}
7. 2 spring data jpa方法命名规范
1)命名规范参考下图:
关键字 | 例子 | JPQL snippet |
---|---|---|
And | findByLastNameAndFirstName | …where x.lastname=?1and x.firstname=?2 |
Or | findByLastNameAndFirstName | …where x.lastname=?1 or x.firstname=?2 |
Is,Equals | findByfirstNameIs, findByfirstNameEquals | …where x.firstname=?1 |
Between | findByBirthDateBewteem | …where x.birthdate between?1and?2 |
LessThan | findByAgeLessThan | …where x.age < ?1 |
LessThanEqual | findByAgeLessThan | …where x.age <= ?1 |
GreaterThan | findByAgeGreaterThan | …where x.age >?1 |
GreaterThanEqual | findByAgeGreaterThan | …where x.age >= ? |
After | findByBirthDateAfter | …where x.birthdate >?1 |
Before | findByBirthDateBefore | …where x.birthdate <?1 |
IsNull | findByFistNameIsNull | …where x.firstname is null |
IsNotNull,NotNull | findByFirstNameNotNull | …where x.firstname is not null |
2)测试
2.1)
package com.yl.jpa.dao;
import com.yl.jpa.model.Book;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface BookDao extends JpaRepository<Book,Long> {
//根据某个属性查询列表信息
List<Book> findBookByAuthorEquals(String author);
}
2.2)
@Test
void test4() {
List<Book> books = bookDao.findBookByAuthorEquals("小明");
System.out.println(books);
}
7. 3 spring data jpa自定义查询,更新等操作
1)自定义查询,在Dao接口里定义
//自定义查询,查询id最大的那条数据
@Query(nativeQuery = true,value = "select * from t_book where id = (select max(id) from t_book)")
Book getMaxIdBook();
2)测试
@Test
void test5() {
Book book = bookDao.getMaxIdBook();
System.out.println(book);
}
3)自定义更新操作,一定要加事务才行
3.1)dao
//自定义更新
//@Query(value = "update t_book set name = ?1, author = ?2, publish_date = ?3 where id = ?4")
@Query(value = "update t_book set name = :name, author = :author, publish_date = :publishDate where id = :id")
@Modifying
void updateById(String name, String author, Date publishDate,Long id);
3.2)service
package com.yl.jpa.service;
import com.yl.jpa.dao.BookDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.Date;
@Service
public class BookService {
@Autowired
BookDao bookDao;
@Transactional
public void updateById(String name, String author, Date publishDate,Long id) {
bookDao.updateById(name,author,publishDate,id);
}
}
4)测试
@Test
void test6() {
bookService.updateById("火影","小白",new Date(),3L);
}
7. 4 spring data jpa多数据源配置
1)项目结构
2)pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.yl</groupId>
<artifactId>jpautil</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>jpautil</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.19</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3)application.properties
# 数据库配置
spring.datasource.one.username=root
spring.datasource.one.password=123456
spring.datasource.one.jdbcurl=jdbc:mysql://192.168.244.129:33061/demo1?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.two.username=root
spring.datasource.two.password=123456
spring.datasource.two.jdbcurl=jdbc:mysql://192.168.244.129:33061/demo2?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai&useSSL=false
# jpa配置
spring.jpa.database=mysql
# 是否显示在控制台打印sql
spring.jpa.show-sql=true
# 使用哪个平台
spring.jpa.database-platform=mysql
# 修改实体类,数据的表是否也是跟着更新
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
4)model
package com.yl.jpautil.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity(name = "user")
public class User {
@Id
@GeneratedValue
private Long id;
@Column(name = "user_name")
private String userName;
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", password='" + password + '\'' +
'}';
}
}
5)数据源配置
package com.yl.jpautil.config;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
/**
* 数据源配置
*/
@Configuration
public class DataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource.one")
@Primary
DataSource dsOne() {
return new HikariDataSource();
}
@Bean
@ConfigurationProperties(prefix = "spring.datasource.two")
DataSource dsTwo() {
return new HikariDataSource();
}
}
6)jpa配置
package com.yl.jpautil.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionManager;
import javax.sql.DataSource;
/**
* jpa的配置
*/
@Configuration
@EnableJpaRepositories(basePackages = "com.yl.jpautil.dao1",entityManagerFactoryRef = "localContainerEntityManagerFactoryBean1",transactionManagerRef = "platformTransactionManager1")
public class JpaConfigOne {
@Autowired
@Qualifier("dsOne")
DataSource ds;
@Autowired
JpaProperties jpaProperties;
@Bean
@Primary
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean1(EntityManagerFactoryBuilder builder) {
return builder.dataSource(ds)
.packages("com.yl.jpautil.model")
.properties(jpaProperties.getProperties())
.persistenceUnit("pu1")
.build();
}
@Bean
PlatformTransactionManager platformTransactionManager1(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(localContainerEntityManagerFactoryBean1(builder).getObject());
}
}
package com.yl.jpautil.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
/**
* jpa的配置
*/
@Configuration
@EnableJpaRepositories(basePackages = "com.yl.jpautil.dao2",entityManagerFactoryRef = "localContainerEntityManagerFactoryBean2",transactionManagerRef = "platformTransactionManager2")
public class JpaConfigTwo {
@Autowired
@Qualifier("dsTwo")
DataSource ds;
@Autowired
JpaProperties jpaProperties;
@Bean
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean2(EntityManagerFactoryBuilder builder) {
return builder.dataSource(ds)
.packages("com.yl.jpautil.model")
.properties(jpaProperties.getProperties())
.persistenceUnit("pu2")
.build();
}
@Bean
PlatformTransactionManager platformTransactionManager2(EntityManagerFactoryBuilder builder) {
return new JpaTransactionManager(localContainerEntityManagerFactoryBean2(builder).getObject());
}
}
7)dao1
package com.yl.jpautil.dao1;
import com.yl.jpautil.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDao1 extends JpaRepository<User,Long> {
}
8)dao2
package com.yl.jpautil.dao2;
import com.yl.jpautil.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDao2 extends JpaRepository<User,Long> {
}
9)测试
package com.yl.jpautil;
import com.yl.jpautil.dao1.UserDao1;
import com.yl.jpautil.dao2.UserDao2;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class JpautilApplicationTests {
@Autowired
UserDao1 userDao1;
@Autowired
UserDao2 userDao2;
@Test
void contextLoads() {
System.out.println(userDao1.findAll());
System.out.println(userDao2.findAll());
}
}
10)测试结果