SpringBoot:整合持久化层

2023-11-11 09:41

本文主要是介绍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&amp
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&amp
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&amp
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&amp
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&amp
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&amp
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&amp
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:整合持久化层的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/389181

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听

在cscode中通过maven创建java项目

在cscode中创建java项目 可以通过博客完成maven的导入 建立maven项目 使用快捷键 Ctrl + Shift + P 建立一个 Maven 项目 1 Ctrl + Shift + P 打开输入框2 输入 "> java create"3 选择 maven4 选择 No Archetype5 输入 域名6 输入项目名称7 建立一个文件目录存放项目,文件名一般为项目名8 确定