本文主要是介绍SpringBoot:整合持久化层,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1,单数据源
1.1,整合Jdbc
JdbcTemplate是Spring提供的一套JDBC模板框架,利用AOP技术来解决使用JDBC时大量重复代码的问题。JdbcTemplate虽然没有MyBatis那么灵活,但是比直接使用JDBC要方便很多。Spring Boot中对JdbcTemplate的使用提供了自动化配置类JdbcTemplateAutoConfiguration。
1.1.1,创建项目
创建SpringBoot项目,并添加依赖。
<?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.4.0</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</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>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.20</version></dependency><!--连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.9</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></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>
在application.properties中配置数据库基本连接信息。
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8& spring.datasource.username=root spring.datasource.password=123456
1.1.2,Pojo+Controller+Service
package com.example.demo;public class Book {private Integer id;private String name;private String author;@Overridepublic String toString() {return "Book{" +"id=" + id +", name='" + name + '\'' +", author='" + author + '\'' +'}';}public Integer getId() {return id;}public void setId(Integer 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;} }
package com.example.demo;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;import java.util.List; @RestController public class BookController {@AutowiredBookService bookService;@GetMapping("/bookOps")public void bookOps() {Book b1 = new Book();b1.setId(99);b1.setName("西厢记");b1.setAuthor("王实甫");int i = bookService.addBook(b1);System.out.println("addBook>>>" + i);Book b2 = new Book();b2.setId(1);b2.setName("朝花夕拾");b2.setAuthor("鲁迅");int updateBook = bookService.updateBook(b2);System.out.println("updateBook>>>"+updateBook);Book b3 = bookService.getBookById(1);System.out.println("getBookById>>>"+b3);int delete = bookService.deleteBookById(2);System.out.println("deleteBookById>>>"+delete);List<Book> allBooks = bookService.getAllBooks();System.out.println("getAllBooks>>>"+allBooks);} }
package com.example.demo;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service;import java.util.List; @Service public class BookService {@AutowiredBookDao bookDao;public int addBook(Book book) {return bookDao.addBook(book);}public int updateBook(Book book) {return bookDao.updateBook(book);}public int deleteBookById(Integer id) {return bookDao.deleteBookById(id);}public Book getBookById(Integer id) {return bookDao.getBookById(id);}public List<Book> getAllBooks() {return bookDao.getAllBooks();} }
1.1.3,Dao
package com.example.demo;import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository;import java.util.List;@Repository public class BookDao {@AutowiredJdbcTemplate jdbcTemplate;public int addBook(Book book) {return jdbcTemplate.update("INSERT INTO book(name,author) VALUES (?,?)",book.getName(), book.getAuthor());}public int updateBook(Book book) {return jdbcTemplate.update("UPDATE book SET name=?,author=? WHERE id=?",book.getName(), book.getAuthor(), book.getId());}public int deleteBookById(Integer id) {return jdbcTemplate.update("DELETE FROM book WHERE id=?", id);}public Book getBookById(Integer id) {return jdbcTemplate.queryForObject("select * from book where id=?",new BeanPropertyRowMapper<>(Book.class), id);}public List<Book> getAllBooks() {return jdbcTemplate.query("select * from book",new BeanPropertyRowMapper<>(Book.class));} }
update/batchUpdate:完成增删改;query/queryForObject:查询;execute:可以用来执行所有的方法;
在执行查询操作时,需要有一个RowMapper将查询出来的列和实体类中的属性一一对应起来。如果列名和属性名相同,可以直接使用BeanPropertyRowMapper;如果列名和属性名不同,就需要开发者自己实现RowMapper接口,将列和实体名一一对应起来。
1.2,整合Hibernate
1.2.1,创建项目
创建项目,添加依赖。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!--数据库驱动--> <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.20</version> </dependency> <!--连接池--> <dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.9</version> </dependency>
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8& spring.datasource.username=root spring.datasource.password=123456 #显示sqL代码 spring.jpa.show-sql=true spring.jpa.database=mysql #自动建表,自动更新 spring.jpa.hibernate.ddl-auto=update
1.2.2,Pojo+Controller+Service
package com.example.demo.model;import javax.persistence.*; @Entity(name = "t_book") public class Book {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Integer id;@Column(name = "book_name",nullable = false)private String name;private String author;private Float price;@Transient //不会再数据库中产生private String description;@Overridepublic String toString() {return "Book{" +"id=" + id +", name='" + name + '\'' +", author='" + author + '\'' +", price=" + price +", description='" + description + '\'' +'}';}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public Integer getId() {return id;}public void setId(Integer 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 Float getPrice() {return price;}public void setPrice(Float price) {this.price = price;} }
package com.example.demo.controller;import com.example.demo.model.Book; import com.example.demo.service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class BookController {@AutowiredBookService bookService;@GetMapping("/search")public void search() {Book b = bookService.getBook(1);System.out.println("b:"+b.toString());}@GetMapping("/save")public void save() {Book book = new Book();book.setAuthor("鲁迅");book.setName("呐喊");book.setPrice(23F);bookService.addBook(book);} }
package com.example.demo.service;import com.example.demo.dao.BookDao; import com.example.demo.model.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class BookService {@AutowiredBookDao bookDao;public void addBook(Book book) {bookDao.save(book);}public Book getBook(Integer id){return bookDao.getBook(id);} }
1.2.3,Dao
package com.example.demo.dao;import com.example.demo.model.Book; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List;public interface BookDao extends JpaRepository<Book,Integer>{@Query("select b from t_book b where b.id=:id")Book getBook( @Param("id") Integer id);}
1.3,整合MyBatis
1.3.1,创建项目
<?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.4.0</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</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</groupId><artifactId>mybatis-spring</artifactId><version>2.0.5</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.1.9</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.20</version></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>
在Maven工程中,XML配置文件建议写在resources目录下,但是上文的Mapper.xml文件写在包下了,在Maven运行过程中会忽略包下的XML文件,因此需要在pom.xml文件中重新指明资源文件的位置。
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?serverTimezone=GMT%2B8& spring.datasource.username=root spring.datasource.password=123456
1.3.2,Pojo+Controller+Service
package com.example.demo.Pojo;public class Book {private Integer id;private String name;private String author;public Integer getId() {return id;}public void setId(Integer 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;} }
package com.example.demo.Controller; import com.example.demo.Pojo.Book; import com.example.demo.Service.BookService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;@RestController public class BookController {@AutowiredBookService bookService;@GetMapping("/selectBook")public Book selectBook(){return bookService.selectBook();} }
package com.example.demo.Service; import com.example.demo.Dao.BookMapper; import com.example.demo.Pojo.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class BookService {@AutowiredBookMapper bookDao;public Book selectBook(){return bookDao.selectBook();} }
1.3.3,Dao
package com.example.demo.Dao;import com.example.demo.Pojo.Book; import org.apache.ibatis.annotations.Mapper; import org.springframework.stereotype.Repository;@Repository @Mapper public interface BookMapper {Book selectBook(); }
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.demo.Dao.BookMapper"><select id="selectBook" resultType="com.example.demo.Pojo.Book">select * from book;</select> </mapper>
如果不想每个Dao层下的包都加上Mapper,只需要在启动类上添加MapperScan
@SpringBootApplication @MapperScan("com.example.demo.Dao") public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}
2,多数据源
采用不同数据库实例中的多个库,或者同一个数据库实例中多个不同的库。
2.1,整合JDBC
2.1.1,配置数据库连接和POM.XML
application.properties
server.port=8081 server.error.path=/error server.servlet.session.timeout=30m #数据源1 spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.one.url=jdbc:mysql://127.0.0.1:3306/test1?serverTimezone=GMT%2B8& spring.datasource.one.username=root spring.datasource.one.password=123456 #数据源2 spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.two.url=jdbc:mysql://127.0.0.1:3306/test2?serverTimezone=GMT%2B8& spring.datasource.two.username=root spring.datasource.two.password=123456
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.4.0</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</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>1.3.2</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><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.17</version></dependency></dependencies><build><!--在Maven中,xml配置文件建议写在resource中,但是为了统一Dao层,添加如下配置,防止Maven在运行时忽略包下的xml文件--><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>
2.1.2,配置数据源和JdbcTemplate
package com.example.demo.Config;import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; 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@Primary@ConfigurationProperties("spring.datasource.one") //表示使用不同前缀的配置文件来创建不同的DataSource实例。DataSource dsOne() {return DruidDataSourceBuilder.create().build();}@Bean@ConfigurationProperties("spring.datasource.two")DataSource dsTwo() {return DruidDataSourceBuilder.create().build();} }
package com.example.demo.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 {@BeanJdbcTemplate jdbcTemplateOne(@Qualifier("dsOne") DataSource dataSource) {return new JdbcTemplate(dataSource);}@BeanJdbcTemplate jdbcTemplateTwo(@Qualifier("dsTwo") DataSource dataSource) {return new JdbcTemplate(dataSource);} }
2.1.3,Controller
package com.example.demo.Controller; import com.example.demo.Pojo.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;import javax.annotation.Resource; import java.util.List;@RestController public class BookController {@Resource(name = "jdbcTemplateOne")JdbcTemplate jdbcTemplateOne;@Resource(name = "jdbcTemplateTwo")JdbcTemplate jdbcTemplateTwo;@GetMapping("/test")public void test(){List<Book> books1 = jdbcTemplateOne.query("select * from book",new BeanPropertyRowMapper<>(Book.class));List<Book> books2 = jdbcTemplateTwo.query("select * from book",new BeanPropertyRowMapper<>(Book.class));System.out.println(books1.get(0).getName());System.out.println(books2.get(0).getName());} }
2.2,整合Mybatis
2.2.1,配置Mybatis
将上面的pom.xml中的jdbc依赖换成下面的mybatis依赖。
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version> </dependency>
package com.example.demo.Config;import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; 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@Primary@ConfigurationProperties("spring.datasource.one") //表示使用不同前缀的配置文件来创建不同的DataSource实例。DataSource dsOne() {return DruidDataSourceBuilder.create().build();}@Bean@ConfigurationProperties("spring.datasource.two")DataSource dsTwo() {return DruidDataSourceBuilder.create().build();} }
package com.example.demo.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.annotation.Resource; import javax.sql.DataSource;@Configuration @MapperScan(value = "com.example.demo.Mapper1",sqlSessionFactoryRef = "sqlSessionFactoryBean1") public class MyBatisConfigOne {@Resource(description = "dsOne")DataSource dsOne;@BeanSqlSessionFactory sqlSessionFactoryBean1() throws Exception{SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();factoryBean.setDataSource(dsOne);return factoryBean.getObject();}@BeanSqlSessionTemplate sqlSessionTemplate1() throws Exception{return new SqlSessionTemplate(sqlSessionFactoryBean1());}}
package com.example.demo.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.annotation.Resource; import javax.sql.DataSource;@Configuration @MapperScan(value = "com.example.demo.Mapper2",sqlSessionFactoryRef = "sqlSessionFactoryBean2") public class MyBatisConfigTwo {@Resource(description = "dsTwo")DataSource dsTwo;@BeanSqlSessionFactory sqlSessionFactoryBean2() throws Exception{SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();factoryBean.setDataSource(dsTwo);return factoryBean.getObject();}@BeanSqlSessionTemplate sqlSessionTemplate2() throws Exception{return new SqlSessionTemplate(sqlSessionFactoryBean2());}}
2.2.2,Controller
package com.example.demo.Controller; import com.example.demo.Mapper1.BookMapper; import com.example.demo.Mapper2.BookMapper2; import com.example.demo.Pojo.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;import java.util.List;@RestController public class BookController {@AutowiredBookMapper bookMapper1;@AutowiredBookMapper2 bookMapper2;@GetMapping("/test")public void test(){List<Book> books1 = bookMapper1.getAllBooks();List<Book> books2 = bookMapper2.getAllBooks2();System.out.println(books1.get(0).getName());System.out.println(books2.get(0).getName());} }
2.2.3,Mapper
package com.example.demo.Mapper1;import com.example.demo.Pojo.Book; import org.springframework.stereotype.Repository;import java.util.List; @Repository public interface BookMapper {List<Book> getAllBooks(); }<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.example.demo.Mapper1.BookMapper"><select id="getAllBooks" resultType="com.example.demo.Pojo.Book">select * from book;</select> </mapper>
2.3,整合Hibernate
2.3.1,Config
不再写JpaConfigTwo,跟1一模一样。
package com.example.demo.Config;import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; 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@Primary@ConfigurationProperties("spring.datasource.one") //表示使用不同前缀的配置文件来创建不同的DataSource实例。DataSource dsOne() {return DruidDataSourceBuilder.create().build();}@Bean@ConfigurationProperties("spring.datasource.two")DataSource dsTwo() {return DruidDataSourceBuilder.create().build();} }
package com.example.demo.Config;import org.springframework.beans.factory.annotation.Autowired; 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.annotation.EnableTransactionManagement; import javax.annotation.Resource; import javax.sql.DataSource;@Configuration @EnableTransactionManagement @EnableJpaRepositories(basePackages = "com.example.demo.dao1",entityManagerFactoryRef = "entityManagerFactoryBeanOne",transactionManagerRef = "platformTransactionManagerOne") public class JpaConfigOne {@Resource(name = "dsOne")DataSource dsOne;@AutowiredJpaProperties jpaProperties;@Bean@PrimaryLocalContainerEntityManagerFactoryBean entityManagerFactoryBeanOne(EntityManagerFactoryBuilder builder) {return builder.dataSource(dsOne).properties(jpaProperties.getProperties()).packages("com.example.demo.Pojo").persistenceUnit("pu1").build();}@BeanPlatformTransactionManager platformTransactionManagerOne(EntityManagerFactoryBuilder builder) {LocalContainerEntityManagerFactoryBean factoryOne = entityManagerFactoryBeanOne(builder);return new JpaTransactionManager(factoryOne.getObject());} }
2.3.2,pojo+dao
package com.example.demo.Pojo;import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity(name = "book") public class Book {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)private Integer id;private String name;private String author;public Integer getId() {return id;}public void setId(Integer 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;} }
package com.example.demo.dao1;import com.example.demo.Pojo.Book; import org.springframework.data.jpa.repository.JpaRepository; public interface BookDao extends JpaRepository<Book,Integer>{ }
2.3.3,Controller+application.properties+pom.xml
package com.example.demo;import com.example.demo.Pojo.Book; import com.example.demo.dao1.BookDao; import com.example.demo.dao2.BookDao2; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class BookController {@AutowiredBookDao userDao;@AutowiredBookDao2 userDao2;@GetMapping("/test1")public void test1() {Book u1 = new Book();u1.setName("鲁迅");u1.setAuthor("男");userDao.save(u1);Book u2 = new Book();u2.setName("泰戈尔");u2.setAuthor("男");userDao2.save(u2);} }
server.port=8081 server.error.path=/error server.servlet.session.timeout=30m spring.jpa.properties.databse=mysql spring.jpa.properties..hibernate.hbm2ddl.auto=update spring.jpa.properties.show-sql=true #数据源1 spring.datasource.one.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.one.url=jdbc:mysql://127.0.0.1:3306/test1?serverTimezone=GMT%2B8& spring.datasource.one.username=root spring.datasource.one.password=123456 #数据源2 spring.datasource.two.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.two.url=jdbc:mysql://127.0.0.1:3306/test2?serverTimezone=GMT%2B8& spring.datasource.two.username=root spring.datasource.two.password=123456
<?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.4.0</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.example</groupId><artifactId>demo</artifactId><version>0.0.1-SNAPSHOT</version><name>demo</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.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId><version>2.4.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.1.17</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><scope>test</scope></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build> </project>
这篇关于SpringBoot:整合持久化层的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!