SpringBoot3+JPA+MySQL实现多数据源的读写分离(基于EntityManagerFactory)

1、简介

在Spring Boot中配置多个数据源并实现自动切换EntityManager,这里我编写了一个RoutingEntityManagerFactory和AOP(面向切面编程)的方式来实现。

这里我配置了两个数据源:primary和secondary,其中primary主数据源用来写入数据,secondary从数据源用来读取数据。

注意1: 使用Springboot3的读写分离,首先要保证主库和从库已经配置好了 数据同步,否则会导致数据不一致。
当然如果仅仅是测试的话,不同步就不影响了

注意2: SpringBoot3的JDK不能低于17
我使用的JDK版本

openjdk version "20.0.2" 2023-07-18
OpenJDK Runtime Environment (build 20.0.2+9-78)
OpenJDK 64-Bit Server VM (build 20.0.2+9-78, mixed mode, sharing)

2、数据库说明

这里我使用了本机的同一个mysql上的两个不同的数据库,在实际环境中这两个库应该是分别处于不同的服务器上,同时应该已经配置好了主从复制或主备,保证了数据的一致性,不然读写分离就没有意义了

数据库名称JDBC-URL说明
primary_dbjdbc:mysql://localhost:3306/primary_db这个是主库,设计为写入数据库
secondary_dbjdbc:mysql://localhost:3306/secondary_db这个是从库,设计为读取数据库

提示:虽然这里我使用的是MySQL数据库,但是在实际的开发过程中,可以替换为Postgresql或oracle等其他关系型数据库,只需要做很小的改动就可以使用了

3、准备工作

3.1、添加依赖

在你的项目里添加如下依赖

<!-- Spring Web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- AOP -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

<!-- JPA -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- MySQL -->
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.3.0</version>
</dependency>


<!-- druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.22</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

完整的pom.xml文件

下面是我在编写代码时候的完整的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>3.2.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.ts</groupId>
    <artifactId>springboot3-jpa-read-write-separation-mysql2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot3-jpa-read-write-separation-mysql2</name>
    <description>springBoot3 + JPA + MySQL 实现读写分离</description>
    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- Spring Boot Starter AOP for @Transactional annotations -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- MySQL Database -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <version>8.3.0</version>
        </dependency>


        <!-- druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.22</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3.2、准备的SQL

-- 用户表
CREATE TABLE userinfo (
  id int AUTO_INCREMENT PRIMARY KEY,
  name varchar(50),
  age smallint,
  gender varchar(3),
  entry_date timestamp
);

-- 测试数据
INSERT INTO userinfo(name,age,gender,entry_date) VALUES
('刘峰',24,'男','2024-02-28 12:01:01'),
('舒航',25,'女','2024-02-28 12:01:01'),
('张明',26,'男','2024-02-29 12:01:01'),
('徐媛',28,'女','2024-02-29 12:01:01'),
('舒莱',29,'女','2023-07-30 12:01:01'),
('唐力',30,'男','2023-08-05 12:01:01'),
('唐莉',29,'女','2023-06-05 12:01:01'),
('王乐',27,'男','2023-07-01 12:01:01'),
('张萌',32,'女','2023-07-02 12:01:01'),
('程媛',25,'女','2023-08-02 12:01:01'),
('嫪玉',35,'女','2023-08-01 10:00:00'),
('贾茹',26,'女','2023-10-03 12:01:01'),
('胡安',25,'男','2023-11-09 12:01:01'),
('刘伟',27,'男','2023-07-09 12:01:01');

3.3、application.yml中定义多数据源配置

application.yml中定义每个数据源的连接信息。

spring:
  jpa:
    database: mysql
    show-sql: true

  datasource:
    #主数据源 , 写入数据库
    primary:
      url: jdbc:mysql://localhost:3306/primary_db?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: root

    # 次数据源 , 读取数据库
    secondary:
      url: jdbc:mysql://localhost:3306/secondary_db?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
      driver-class-name: com.mysql.jdbc.Driver
      username: root
      password: root


4、创建动态数据源

4.1、主数据源配置

package com.ts.config;


import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 *  主数据源配置
 * @author zhouq
 * @since 15:26 2024/03/21
 **/
@Configuration(proxyBeanMethods = false)
@EnableJpaRepositories(
        basePackages = "com.ts.service",
        entityManagerFactoryRef = "primaryEntityManagerFactory"
)
public class PrimaryDataSourceConfig {


    @Autowired
    private JpaProperties jpaProperties;



    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        //return DataSourceBuilder.create().build();
        return new DruidDataSource();
    }

    //LocalContainerEntityManagerFactoryBean
    @Bean
    public Object primaryEntityManagerFactory(DataSource primaryDataSource,
                                                                            JpaProperties primaryJpaProperties) {
        EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(primaryJpaProperties);
        return builder.dataSource(primaryDataSource).packages("com.ts.model")
                .persistenceUnit("primaryDataSource").build();
    }

    private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder(JpaProperties jpaProperties) {
        JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter(jpaProperties);
        return new EntityManagerFactoryBuilder(jpaVendorAdapter, jpaProperties.getProperties(), null);
    }

    private JpaVendorAdapter createJpaVendorAdapter(JpaProperties jpaProperties) {
        // ... map JPA properties as needed
        return new HibernateJpaVendorAdapter();
    }


}

4.2、次要数据源配置

package com.ts.config;


import com.alibaba.druid.pool.DruidDataSource;
import jakarta.persistence.EntityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * 次要数据源配置
 * @author zhouq
 * @since 15:25 2024/03/21
 **/
@Configuration
@EnableJpaRepositories(
        basePackages = "com.ts.service",
        entityManagerFactoryRef = "secondaryEntityManagerFactory"
)
public class SecondaryDataSourceConfig {

    @Autowired
    private JpaProperties jpaProperties;


    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.secondary")
    public DataSource secondaryDataSource() {
        //return DataSourceBuilder.create().build();
        return new DruidDataSource();
    }

    // LocalContainerEntityManagerFactoryBean
    @Bean
    public Object secondaryEntityManagerFactory(DataSource secondaryDataSource,
                                                                              JpaProperties secondaryJpaProperties) {
        EntityManagerFactoryBuilder builder = createEntityManagerFactoryBuilder(secondaryJpaProperties);
        return builder.dataSource(secondaryDataSource).packages("com.ts.model")
                .persistenceUnit("secondaryDataSource").build();
    }

    private EntityManagerFactoryBuilder createEntityManagerFactoryBuilder(JpaProperties jpaProperties) {
        JpaVendorAdapter jpaVendorAdapter = createJpaVendorAdapter(jpaProperties);
        return new EntityManagerFactoryBuilder(jpaVendorAdapter, jpaProperties.getProperties(), null);
    }

    private JpaVendorAdapter createJpaVendorAdapter(JpaProperties jpaProperties) {
        // ... map JPA properties as needed
        return new HibernateJpaVendorAdapter();
    }
    
}

5、全局EntityManager配置

5.1、创建EntityManager线程工具类

EntityManagerContextHolder是一个用来保存当前线程的EntityManager名称的工具类。

package com.ts.config;


/**
 * 用来保存当前线程的EntityManagerFactory名称 的工具类
 * @author zhouq
 * @since 14:29 2024/03/20
 **/
public class EntityManagerContextHolder {
    private static final ThreadLocal<String> contextHolder = new ThreadLocal<>();

    public static void setEntityManagerFactoryType(String entityManagerFactoryType) {
        contextHolder.set(entityManagerFactoryType);
    }

    public static String getEntityManagerFactoryType() {
        return contextHolder.get();
    }

    public static void clearEntityManagerFactoryType() {
        contextHolder.remove();
    }
}

5.2、创建数RoutingEntityManagerFactory路由(管理多个EntityManager)

package com.ts.config;

import jakarta.persistence.*;
import jakarta.persistence.criteria.CriteriaBuilder;
import jakarta.persistence.metamodel.Metamodel;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import java.util.Map;


/**
 *  动态切换EntityManagerFactory
 *  EntityManagerFactory路由类
 * @author zhouq
 * @since 14:54 2024/03/21
 **/
public class RoutingEntityManagerFactory implements EntityManagerFactory{
    @Nullable
    private Map<String, Object> targetEntityManagerFactorys;
    @Nullable
    private Object defaultTargetEntityManagerFactory;

    @Nullable
    public Map<String, Object> getTargetEntityManagerFactorys() {
        return targetEntityManagerFactorys;
    }

    public void setTargetEntityManagerFactorys(@Nullable Map<String, Object> targetEntityManagerFactorys) {
        this.targetEntityManagerFactorys = targetEntityManagerFactorys;
    }

    @Nullable
    public Object getDefaultTargetEntityManagerFactory() {
        return defaultTargetEntityManagerFactory;
    }

    public void setDefaultTargetEntityManagerFactory(@Nullable Object defaultTargetEntityManagerFactory) {
        this.defaultTargetEntityManagerFactory = defaultTargetEntityManagerFactory;
    }

    public String determineCurrentLookupKey() {
        // 如果不使用读写分离,这里也可以做一个简单的负载均衡策略
        String entityManagerFactoryType = EntityManagerContextHolder.getEntityManagerFactoryType();
        //System.out.println("当前使用的数据源是:" + entityManagerFactoryType);
        return entityManagerFactoryType;
    }

    public EntityManagerFactory determineTargetEntityManagerFactory() {
        Assert.notNull(this.targetEntityManagerFactorys, "targetEntityManagerFactory router not initialized");
        Object lookupKey = this.determineCurrentLookupKey();
        EntityManagerFactory entityManagerFactory = (EntityManagerFactory)this.targetEntityManagerFactorys.get(lookupKey);
        if (entityManagerFactory == null && lookupKey == null) {
            entityManagerFactory = (EntityManagerFactory)this.defaultTargetEntityManagerFactory;
        }

        if (entityManagerFactory == null) {
            throw new IllegalStateException("Cannot determine target EntityManagerFactory for lookup key [" + lookupKey + "]");
        } else {
            return entityManagerFactory;
        }
    }

    //---------------------下面的方法都是EntityManagerFactory接口的实现------------------------------------
    @Override
    public EntityManager createEntityManager() {
        return this.determineTargetEntityManagerFactory().createEntityManager();
    }

    @Override
    public EntityManager createEntityManager(Map map) {
        return this.determineTargetEntityManagerFactory().createEntityManager(map);
    }

    @Override
    public EntityManager createEntityManager(SynchronizationType synchronizationType) {
        return this.determineTargetEntityManagerFactory().createEntityManager(synchronizationType);
    }

    @Override
    public EntityManager createEntityManager(SynchronizationType synchronizationType, Map map) {
        return this.determineTargetEntityManagerFactory().createEntityManager(synchronizationType,map);
    }

    @Override
    public CriteriaBuilder getCriteriaBuilder() {
        return this.determineTargetEntityManagerFactory().getCriteriaBuilder();
    }

    @Override
    public Metamodel getMetamodel() {
        return this.determineTargetEntityManagerFactory().getMetamodel();
    }

    @Override
    public boolean isOpen() {
        return this.determineTargetEntityManagerFactory().isOpen();
    }

    @Override
    public void close() {
        this.determineTargetEntityManagerFactory().close();
    }

    @Override
    public Map<String, Object> getProperties() {
        return this.determineTargetEntityManagerFactory().getProperties();
    }

    @Override
    public Cache getCache() {
        return this.determineTargetEntityManagerFactory().getCache();
    }

    @Override
    public PersistenceUnitUtil getPersistenceUnitUtil() {
        return this.determineTargetEntityManagerFactory().getPersistenceUnitUtil();
    }

    @Override
    public void addNamedQuery(String s, Query query) {
        this.determineTargetEntityManagerFactory().addNamedQuery(s,query);
    }

    @Override
    public <T> T unwrap(Class<T> aClass) {
        return this.determineTargetEntityManagerFactory().unwrap(aClass);
    }

    @Override
    public <T> void addNamedEntityGraph(String s, EntityGraph<T> entityGraph) {
        this.determineTargetEntityManagerFactory().addNamedEntityGraph(s,entityGraph);
    }
}

5.3、创建EntityManagerFactory全局配置类

package com.ts.config;

import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityManagerFactory;
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.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 *  全局配置实体管理工厂 EntityManagerFactory
 *  配置EntityManagerFactory,确定使用的EntityManagerFactory
 * @author zhouq
 * @since 10:59 2024/03/21
 **/
@Configuration
public class EntityManagerFactoryConfig {

    @Autowired
    @Qualifier("primaryEntityManagerFactory")
    private Object primaryEntityManagerFactory;

    @Autowired
    @Qualifier("secondaryEntityManagerFactory")
    private Object secondaryEntityManagerFactory;


    @Bean
    public EntityManagerFactory entityManager(){
        String dataSourceType = EntityManagerContextHolder.getEntityManagerFactoryType();

        RoutingEntityManagerFactory routingEntityManagerFactory = new RoutingEntityManagerFactory();

        Map<String, Object> targetEntityManagerFactorys = new HashMap<String, Object>();

        targetEntityManagerFactorys.put("primary", primaryEntityManagerFactory);  //主实体管理工厂
        targetEntityManagerFactorys.put("secondary", secondaryEntityManagerFactory); //次要实体管理工厂

        routingEntityManagerFactory.setTargetEntityManagerFactorys(targetEntityManagerFactorys);// 配置实体管理工厂
        routingEntityManagerFactory.setDefaultTargetEntityManagerFactory(primaryEntityManagerFactory);// 设置默认实体管理工厂

        return routingEntityManagerFactory;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        JpaTransactionManager tm = new JpaTransactionManager();
        tm.setEntityManagerFactory(entityManager());
        return tm;
    }

}

6、使用AOP实现EntityManager自动切换

6.1、创建AOP切面注入EntityManager类型

通过AOP在方法执行前设置EntityManagerFactory,并在方法执行后清除。

package com.ts.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * 使用AOP注入EntityManager类型
 * 通过AOP在方法执行前设置EntityManager,并在方法执行后清除。
 * @author zhouq
 * @since 14:25 2024/03/20
 **/
@Aspect
@Component
public class EntityManagerFactoryAspect {

    @Before("@annotation(dataSource)")
    public void switchDataSource(JoinPoint point, DataSourceSwitch dataSource) {
        //log.info("使用的数据源是:" + dataSource.value());
        System.out.println("使用的数据源是:" + dataSource.value());
        EntityManagerContextHolder.setEntityManagerFactoryType(dataSource.value());
    }

    @After("@annotation(dataSource)")
    public void restoreDataSource(JoinPoint point, DataSourceSwitch dataSource) {
        EntityManagerContextHolder.clearEntityManagerFactoryType();
    }
}

6.2、创建自定义注解用于标注所使用的的

DataSourceSwitch是一个自定义注解,用来标识需要切换数据源的方法。

package com.ts.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 自定义注解,用来标识需要切换数据源的方法
 * @author zhouq
 * @since 14:31 2024/03/20
 **/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSourceSwitch {
    String value() default "primary";
}

7、创建实体类

package com.ts.model;

import jakarta.persistence.*;
import lombok.*;
import lombok.experimental.Accessors;
import java.util.Date;


@Setter
@Getter
@Accessors(chain = true)
@AllArgsConstructor // 全参构造方法
@NoArgsConstructor // 无参构造方法
//@RequiredArgsConstructor
@ToString
@Entity
@Table(name = "userinfo")
public class Userinfo implements java.io.Serializable{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    private String name;
    private int age;
    private String gender;
    private Date entry_date;

}

8、创建Service

创建UserService接口

package com.ts.service;

import com.ts.model.Userinfo;
import java.util.List;


public interface UserService {
    /**
     *  获取所有
     * @author zhouq
     * @since 13:33 2024/03/20
     * @return java.util.List<com.ts.model.Userinfo>
     **/
    List<Userinfo> getAll();

    /**
     * 查找包含姓名的用户
     * @author zhouq
     * @since 13:34 2024/03/20
     * @param name 姓名
     * @return java.util.List<com.ts.model.Userinfo>
     **/
    List<Userinfo> queryWithName(String name);


    /**
     *  添加用户
     * @author zhouq
     * @since 13:39 2024/03/20
     * @return java.util.List<com.ts.model.Userinfo>
     **/
    void addUser(Userinfo userinfo);

    /**
     * 按照id删除
     * @author zhouq
     * @since 13:55 2024/03/20
     **/
    void deleteUser(int id);

}

创建UserService接口实现类

package com.ts.service.impl;

import com.ts.config.DataSourceSwitch;
import com.ts.model.Userinfo;
import com.ts.service.UserService;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 *  基于EntityManager的实现
 *  这里使用 primary主数据源写入数据,secondary从数据源读取数据
 * @author zhouq
 * @since 11:08 2024/03/21
 **/
@Service
public class UserServiceEntityManagerImpl implements UserService {

    @Autowired
    private EntityManager entityManager;


    /**
     * 获取所有用户
     * 这里使用   @DataSourceSwitch("secondary")  指定 读取的数据源
     * @author zhouq
     * @since 11:21 2024/03/21
     * @return java.util.List<com.ts.model.Userinfo>
     **/
    @Override
    @DataSourceSwitch("secondary")
    public List<Userinfo> getAll() {
        return  entityManager.createQuery("select u from Userinfo u").getResultList();
    }

    /**
     * 查询用户,模糊查询
     * @author zhouq
     * @since 11:20 2024/03/21
     * @return java.util.List<com.ts.model.Userinfo>
     **/
    @Override
    @DataSourceSwitch("secondary")
    public List<Userinfo> queryWithName(String name) {
        Query query = entityManager.createQuery("select u from Userinfo u where u.name like :name");
        query.setParameter("name", "%" + name +"%");

        return query.getResultList();
    }


    /**
     * 添加用户
     * 这里使用   @DataSourceSwitch("primary")  指定写入的数据源
     * @author zhouq
     * @since 11:20 2024/03/21
     **/
    @Override
    @DataSourceSwitch("primary")  //或者 @DataSourceSwitch
    @Modifying
    @Transactional
    public void addUser(Userinfo userinfo) {

        //使用本地原生SQL查询
        Query nativeQuery = entityManager.createNativeQuery("insert into Userinfo(id,name,age,gender) values(:id,:name,:age,:gender)");
        nativeQuery.setParameter("id",userinfo.getId());
        nativeQuery.setParameter("name",userinfo.getName());
        nativeQuery.setParameter("age",userinfo.getAge());
        nativeQuery.setParameter("gender",userinfo.getGender());

        //执行查询
        int i = nativeQuery.executeUpdate();
        if ( i<= 0 ) {
            throw new RuntimeException("添加用户失败!");
        }
    }

    /**
     * 删除用户
     * 这里使用   @DataSourceSwitch("primary")  指定写入的数据源
     * @author zhouq
     * @since 11:19 2024/03/21
     **/
    @Override
    @DataSourceSwitch("primary")  //或者 @DataSourceSwitch
    @Modifying
    @Transactional
    public void deleteUser(int id) {
        //使用本地原生SQL查询
        Query nativeQuery = entityManager.createNativeQuery("delete from Userinfo where id = :id");
        nativeQuery.setParameter("id",id);
        //执行
        int i = nativeQuery.executeUpdate();
        if ( i<= 0 ) {
            throw new RuntimeException("删除用户失败!");
        }
    }

}

9、编写测试类

package com.ts;

import com.ts.model.Userinfo;
import com.ts.service.UserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;

@SpringBootTest
public class UserServiceTest {

    @Autowired
    private UserService service;



    // 测试使用从库读取  查询用户
    @Test
    public void testGetAll() {
        service.getAll().forEach(System.out::println);
        //System.out.println(service);
    }
    // 测试使用从库读取  查询用户
    @Test
    public void testQuery() {
        service.queryWithName("张").forEach(System.out::println);
    }

    // 测试使用主库写入  添加用户
    @Test
    public void testAddUser() {
        service.addUser(new Userinfo(100,"测试用户",25,"男",new Date()));
        System.out.println("添加用户完成");
    }

    // 测试使用主库写入  删除用户
    @Test
    public void testDelete() {
        service.deleteUser(100);
        System.out.println("删除用户完成");
    }

}

小结

关于读写分离网上的示例很多,但是都比较杂乱,而且很多的方法都是基于SpringBoot2或者SpringBoot1的,我这个是基于SpringBoot3.2.3版本实现了,

上面的代码所有的都亲自测试通过,有什么疑问可以留言评论。

几个截图:
1、查询所有
可以看到 使用的数据源是:secondary 使用的是 读 数据源
在这里插入图片描述
2、模糊查询
在这里插入图片描述

3、添加用户
看到 使用的数据源是:primary 使用的是 写 数据源
在这里插入图片描述
4、删除用户
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/486280.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Redis - 高并发场景下的Redis最佳实践_翻过6座大山

文章目录 概述6座大山之_缓存雪崩 &#xff08;缓存全部失效&#xff09;缓存雪崩的两种常见场景如何应对缓存雪崩&#xff1f; 6座大山之_缓存穿透&#xff08;查询不存在的 key&#xff09;缓存穿透的原因解决方案1. 数据校验2. 缓存空值3. 频控4. 使用布隆过滤器 6座大山之_…

hash冲突四种解决办法,hash冲突除了拉链法还有什么?

1. 看hashmap 源码&#xff0c;有个问题&#xff0c;key 存放是 先hash 再与hash值的高16位值 进行异或运算。再与槽位size() 求模取余。如果多个不同的key 得出de数组位置相同。则采用链表依次存储。 2. 那么除了拉链法还有什么其他解决hash冲突的方法呢&#xff1f; a. 建立…

【学习】Web安全测试需要考虑哪些情形

一、数据加密 某些数据需要进行信息加密和过滤后才能在客户端和服务器之间进行传输&#xff0c;包括用户登录密码、信用卡信息等。例如&#xff0c;在登录某银行网站时&#xff0c;该网站必须支持SSL协议&#xff0c;通过浏览器访问该网站时&#xff0c;地址栏的http变成https…

堂哥让我给他做个真人动漫头像

背景 堂哥最喜欢的动漫是死神。他给了我一张死神主角一户的头像&#xff0c;以及自己的头像&#xff0c;希望我产出一张真人动漫头像。 一户的头像&#xff1a; 堂哥自拍照&#xff1a; 最近&#xff0c;有大佬部署了个stable diffusion&#xff0c;正好拿来一试身手。 stab…

vue项目报这个错是 Same `value` exist in the tree: 0008E3000E1A?

警告 "Same value exist in the tree: 0008E3000E1A" 表示在树形选择器中存在相同的值。这通常是由于树形选择器的数据中存在重复的值造成的。就是返回的值中&#xff0c;有俩个id相同

【Redis】数据类型、事务执行、内存淘汰策略

目录 数据类型 Redis事务执行步骤 步骤&#xff1a; redis内存淘汰策略 设置内存淘汰策略 1.设置配置文件 2.通过命令设置 数据类型 官网解释 Understand Redis data types | Redis 首先&#xff0c;Redis 的所有键都是字符串,常用的数据类型有 5 种&#xff1a;Strin…

快速上手 Elasticsearch:Docker Compose 部署详解

最近面试竞争日益激烈&#xff0c;Elasticsearch作为一款广泛应用的中间件&#xff0c;几乎成为面试中必考的知识点。最近&#xff0c;AIGC也备受关注&#xff0c;而好多的AI项目中也采用了Elasticsearch作为向量数据库&#xff0c;因此我们迫切希望学习Elasticsearch。对于学习…

【机器学习】基于变色龙算法优化的BP神经网络分类预测(SSA-BP)

目录 1.原理与思路2.设计与实现3.结果预测4.代码获取 1.原理与思路 【智能算法应用】智能算法优化BP神经网络思路【智能算法】变色龙优化算法&#xff08;CSA)原理及实现 2.设计与实现 数据集&#xff1a; 数据集样本总数2000 多输入多输出&#xff1a;样本特征24&#xff…

工业4.0 底层逻辑

许多场合下&#xff0c;工业4.0 的概念已经被滥用了&#xff0c;它与物联网&#xff0c;工业物联网等概念被滥用一样&#xff0c;几乎什么都往里面装。演变成了一句口号和愿景。许多人并不清楚工业4.0的底层逻辑到底是什么&#xff1f;如何遵循工业4.0 的思想构建新一代智能制造…

社交媒体行业巨头:揭示Facebook的市场地位

引言 随着数字化时代的蓬勃发展&#xff0c;社交媒体已经深刻改变了人们的生活方式和社会交往方式&#xff0c;而Facebook作为其中的领军者&#xff0c;扮演着举足轻重的角色。本文将深入探讨Facebook在社交媒体行业中的市场地位&#xff0c;从用户规模、收入来源、技术创新、…

【Android】美团组件化路由框架WMRouter源码解析

前言 Android无论App开发还是SDK开发&#xff0c;都绕不开组件化&#xff0c;组件化要解决的最大的问题就是组件之间的通信&#xff0c;即路由框架。国内使用最多的两个路由框架一个是阿里的ARouter&#xff0c;另一个是美团的WMRouter。这两个路由框架功能都很强大&#xff0…

智能运维的发展演进

Gartner在2018年提出AIOps&#xff08;Artificial Intelligence for IT Operations&#xff09;&#xff0c;即人工智能在IT运维领域的应用。智能运维在技术方案、平台、场景都更加聚焦&#xff0c;恰逢AI技术飞速发展。用户可以实时监控分析大量的运维数据&#xff0c;预防和防…

python + tensorflow 开局托儿所自动点击脚本

python开局托儿所自动点击脚本 屏幕截图图片数字识别消除算法自动点击 屏幕截图 python 屏幕截图可以使用pyautogui或者PIL。我使用的是PIL中的ImageGrab(要授权)。 image ImageGrab.grab(bbox(0, 0, tool.static_window_width, tool.static_window_height)) image np.arra…

ModbusRTU/TCP/profinet网关在西门子博图软件中无法连接PLC的解决方法

ModbusRTU/TCP/profinet网关在西门子博图软件中无法连接PLC的解决方法 在工业生产现场&#xff0c;ModbusRTU/TCP/profinet网关在与西门子PLC连接时&#xff0c;必须要使用西门子的博图软件来进行配置&#xff0c;博图v17是一个集成软件平台&#xff0c;专业版支持300、400、12…

海外基金牌照的优势及注意事项-华媒舍

一、了解海外基金牌照 在投资领域&#xff0c;海外基金牌照是指投资者可以通过获得海外金融监管机构颁发的许可证&#xff0c;参与海外基金投资。拥有海外基金牌照的投资者可以享受更广泛的投资机会&#xff0c;包括跨境投资、全球资产配置等。 二、海外基金牌照的优势 多元化…

Unity 学习日记 8.2D物理引擎

1.2D刚体的属性和方法 2.碰撞器

还在购买蜘蛛池做SEO?有用吗?

蜘蛛池是什么&#xff1f;租用蜘蛛池对SEO优化到底有没有用&#xff1f;网上很多说法&#xff0c;且各执一词&#xff0c;那些出租蜘蛛池的写的软文不算。站长帮一直本着负责任的态度&#xff0c;从客观的角度&#xff0c;来为大家一一解惑。 本文 虚良SEO 原创&#xff0c;转载…

如何查询网贷大数据信用报告?哪个查询平台更好?

在互联网金融迅速发展的当下&#xff0c;网贷大数据查询平台已成为许多人在申请贷款前的重要工具。然而&#xff0c;随着这些平台的广泛使用&#xff0c;安全问题日益凸显&#xff0c;许多用户反映自己的个人信息在查询过程中被泄露。为了应对这一挑战&#xff0c;本文将探讨如…

fiddler配合夜神模拟器对APP进行抓包

fiddler 配置 设置https Tools – -> Options —> HTTPS 在这里插入图片描述 下载证书&#xff0c;并安装 修改模拟器网络连接 cmd 查看本机本地IP点击模拟器wifi, 长按修改为手动配置&#xff1a; IP 8888使用浏览器&#xff0c;访问IP 8888 下载证书 。点击Fiddler…

RabbitMQ详细讲解

目录 4.0 AMQP协议的回顾 4.1 RabbitMQ支持的消息模型 4.2 引入依赖 4.3 第一种模型(直连) 1. 开发生产者 2. 开发消费者 3. 参数的说明 4.4 第二种模型(work quene) 1. 开发生产者 2.开发消费者-1 3.开发消费者-2 4.测试结果 5.消息自动确认机制 4.5 第三种模型(…
最新文章