Spring-boot多个数据库 - spring插入数据但只保存到一个db

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring-boot多个数据库 - spring插入数据但只保存到一个db相关的知识,希望对你有一定的参考价值。

我真的一直在使用springboot中的多(2)个数据库设置。我花了无数个小时,跟着很多例子,我读过complete documentation。 我觉得很难决定应该在我的代码中添加什么,因为有很多例子都有不同的解决方案。有Spring,Spring-boot,hibernate,jpa,bean,xml文件,注释,腐败依赖。 我想出了一段不会出错并保存数据的代码。但是,只保存主数据库的数据。第二个数据库中的插入是根据sql跟踪发生但没有提交。这里发生了什么? 我还创建了一个简单的控制器类来插入带有http请求的数据,但它有相同的结果:只有db1中的用户被保存,而db2中的产品则没有。如果有人有任何线索,将不胜感激。这让我疯了!我意识到这只是一段简单的代码,但是测试是否可以在更大的项目中使用这种方法。谢谢!

配置:

import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
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.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import com.multidb.db1.enitities.User;
import com.multidb.db2.entities.Product;

import javax.sql.DataSource;

@EnableJpaRepositories
public class DbConfiguration 

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource")
    public DataSourceProperties firstDataSourceProperties() 
        return new DataSourceProperties();
    

    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource.configuration")
    public HikariDataSource firstDataSource() 
        return firstDataSourceProperties().initializeDataSourceBuilder()
                .type(HikariDataSource.class).build();
    

    @Bean
    @ConfigurationProperties("spring.datasource2")
    public DataSourceProperties secondDataSourceProperties() 
        return new DataSourceProperties();
    

    @Bean
    @ConfigurationProperties("spring.datasource2.configuration")
    public BasicDataSource secondDataSource() 
        return secondDataSourceProperties().initializeDataSourceBuilder()
                .type(BasicDataSource.class).build();
    

    //////

    @Primary
    @Bean
    public LocalContainerEntityManagerFactoryBean userEntityManagerFactory(
            EntityManagerFactoryBuilder builder) 
        return builder
                .dataSource(firstDataSource())
                .packages("db1")//User.class
                .persistenceUnit("users")
                .build();
    

    @Bean
    public LocalContainerEntityManagerFactoryBean productEntityManagerFactory(
            EntityManagerFactoryBuilder builder) 
        return builder
                .dataSource(secondDataSource())
                .packages("db2")//Product.class
                .persistenceUnit("products")
                .build();
    


applicaton.properties文件

spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.show-sql=true

logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

spring.datasource.url=jdbc:mysql://localhost/db1?autoReconnect=true&useSSL=false
spring.datasource.username=user
spring.datasource.password=pass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.configuration.maximum-pool-size=30

spring.datasource2.url=jdbc:mysql://localhost/db2?autoReconnect=true&useSSL=false
spring.datasource2.username=user
spring.datasource2.password=pass
spring.datasource2.driver-class-name=com.mysql.jdbc.Driver
spring.datasource2.max-total=30

一个简单的用户类

import javax.persistence.*;

@Entity
@Table
public class User 

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String firstName;

    private String lastName;


    public User(String firstName, String lastName) 
        this.firstName = firstName;
        this.lastName = lastName;
    

    public User() 
        //
    



和产品类

import javax.persistence.*;

@Entity
@Table
public class Product 

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    private double price;

    public Product(String name, double price) 
        this.name = name;
        this.price = price;
    

    public Product() 
        //
    

用户回购

import org.springframework.data.repository.CrudRepository;
import com.multidb.db1.enitities.User;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public interface UserRepository extends CrudRepository<User, Long> 
    //

产品回购


import com.multidb.db2.entities.Product;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;

public interface ProductRepository extends CrudRepository<Product, Long> 
    //


一个简单的datainit类,用于向db写入内容

import com.multidb.db1.repositories.UserRepository;
import com.multidb.db1.enitities.User;
import com.multidb.db2.entities.Product;
import com.multidb.db2.repositories.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class InitData implements ApplicationRunner 

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    public InitData()

    @Override
    public void run(ApplicationArguments args) throws Exception 
        addUser("Johnny", "Depp");
        addProduct("Booze", 5.0);
    

    private void addUser(String firstname, String lastname)
        User user = new User(firstname, lastname);
        userRepository.save(user);
    

    private void addProduct(String name, double price)
        Product product = new Product(name, price);
        productRepository.save(product);
    


Maven依赖项

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>

    <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>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>
    </dependencies>

最后但并非最不重要的输出


  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.3.RELEASE)



2019-04-02 13:20:09.084  INFO 47275 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-04-02 13:20:09.147  INFO 47275 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 56ms. Found 2 repository interfaces.
2019-04-02 13:20:09.466  INFO 47275 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$84774c02] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-04-02 13:20:09.765  INFO 47275 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-04-02 13:20:09.795  INFO 47275 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-04-02 13:20:09.796  INFO 47275 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.16]
2019-04-02 13:20:09.805  INFO 47275 --- [           main] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/Fdoe/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2019-04-02 13:20:09.884  INFO 47275 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-04-02 13:20:09.885  INFO 47275 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1367 ms
2019-04-02 13:20:10.114  INFO 47275 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-04-02 13:20:10.327  INFO 47275 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-04-02 13:20:10.368  INFO 47275 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2019-04-02 13:20:10.423  INFO 47275 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core 5.3.7.Final
2019-04-02 13:20:10.424  INFO 47275 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2019-04-02 13:20:10.553  INFO 47275 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations 5.0.4.Final
2019-04-02 13:20:10.684  INFO 47275 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2019-04-02 13:20:11.209 DEBUG 47275 --- [           main] org.hibernate.SQL                        : drop table if exists hibernate_sequence
Hibernate: drop table if exists hibernate_sequence
2019-04-02 13:20:11.220 DEBUG 47275 --- [           main] org.hibernate.SQL                        : drop table if exists product
Hibernate: drop table if exists product
2019-04-02 13:20:11.222 DEBUG 47275 --- [           main] org.hibernate.SQL                        : drop table if exists user
Hibernate: drop table if exists user
2019-04-02 13:20:11.225 DEBUG 47275 --- [           main] org.hibernate.SQL                        : create table hibernate_sequence (next_val bigint) engine=MyISAM
Hibernate: create table hibernate_sequence (next_val bigint) engine=MyISAM
2019-04-02 13:20:11.228 DEBUG 47275 --- [           main] org.hibernate.SQL                        : insert into hibernate_sequence values ( 1 )
Hibernate: insert into hibernate_sequence values ( 1 )
2019-04-02 13:20:11.230 DEBUG 47275 --- [           main] org.hibernate.SQL                        : insert into hibernate_sequence values ( 1 )
Hibernate: insert into hibernate_sequence values ( 1 )
2019-04-02 13:20:11.231 DEBUG 47275 --- [           main] org.hibernate.SQL                        : create table product (id bigint not null, name varchar(255), price double precision not null, primary key (id)) engine=MyISAM
Hibernate: create table product (id bigint not null, name varchar(255), price double precision not null, primary key (id)) engine=MyISAM
2019-04-02 13:20:11.235 DEBUG 47275 --- [           main] org.hibernate.SQL                        : create table user (id bigint not null, first_name varchar(255), last_name varchar(255), primary key (id)) engine=MyISAM
Hibernate: create table user (id bigint not null, first_name varchar(255), last_name varchar(255), primary key (id)) engine=MyISAM
2019-04-02 13:20:11.239  INFO 47275 --- [           main] o.h.t.schema.internal.SchemaCreatorImpl  : HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@3a7c678b'
2019-04-02 13:20:11.241  INFO 47275 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2019-04-02 13:20:11.651  INFO 47275 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-04-02 13:20:11.695  WARN 47275 --- [           main] aWebConfiguration$JpaWebMvcConfiguration : spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2019-04-02 13:20:11.889  INFO 47275 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-04-02 13:20:11.891  INFO 47275 --- [           main] com.fdoe.multidb.Application            : Started Application in 3.92 seconds (JVM running for 4.308)
2019-04-02 13:20:11.913 DEBUG 47275 --- [           main] org.hibernate.SQL                        : select next_val as id_val from hibernate_sequence for update
Hibernate: select next_val as id_val from hibernate_sequence for update
2019-04-02 13:20:11.928 DEBUG 47275 --- [           main] org.hibernate.SQL                        : update hibernate_sequence set next_val= ? where next_val=?
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
2019-04-02 13:20:11.948 DEBUG 47275 --- [           main] org.hibernate.SQL                        : insert into user (first_name, last_name, id) values (?, ?, ?)
Hibernate: insert into user (first_name, last_name, id) values (?, ?, ?)
2019-04-02 13:20:11.950 TRACE 47275 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [Johnny]
2019-04-02 13:20:11.950 TRACE 47275 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [VARCHAR] - [Depp]
2019-04-02 13:20:11.951 TRACE 47275 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [BIGINT] - [1]
2019-04-02 13:20:11.957 DEBUG 47275 --- [           main] org.hibernate.SQL                        : select next_val as id_val from hibernate_sequence for update
Hibernate: select next_val as id_val from hibernate_sequence for update
2019-04-02 13:20:11.958 DEBUG 47275 --- [           main] org.hibernate.SQL                        : update hibernate_sequence set next_val= ? where next_val=?
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
2019-04-02 13:20:11.959 DEBUG 47275 --- [           main] org.hibernate.SQL                        : insert into product (name, price, id) values (?, ?, ?)
Hibernate: insert into product (name, price, id) values (?, ?, ?)
2019-04-02 13:20:11.959 TRACE 47275 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [Booze]
2019-04-02 13:20:11.960 TRACE 47275 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [DOUBLE] - [5.0]
2019-04-02 13:20:11.960 TRACE 47275 --- [           main] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [BIGINT] - [2]

db1 - 终端/命令行输出

mysql> select * from user;
+----+------------+-----------+
| id | first_name | last_name |
+----+------------+-----------+
|  1 | Johnny     | Depp      |
+----+------------+-----------+
1 row in set (0.00 sec)

mysql> 

db2 - 终端/命令行输出

mysql> select * from product;
Empty set (0.01 sec)

mysql> 
答案

您尚未包含Product Repository和User Repository类,请检查类中的注释

如果是,那么您是否使用了实体管理器然后您是否为实体管理器使用了@PersistenceContext注释

请按照下面的示例,尝试通过复制粘贴代码并查看配置来在本地运行它

Spring Boot + JPA

如果您使用过CRUD存储库您可以参考以下代码

Spring Boot+CRUD Repository+JPA

两者都在我的本地运行

以上是关于Spring-boot多个数据库 - spring插入数据但只保存到一个db的主要内容,如果未能解决你的问题,请参考以下文章

Spring-boot多个数据库 - spring插入数据但只保存到一个db

spring-boot 应用程序不会将夹具加载到多个数据源之一

在春季批处理(spring-boot-1.5.2.RELEASE)中使用多个数据源在启动时引发异常

如何通过使用 JPA + Hibernate 和 Spring-boot 在一个数据库中使用多个模式?

Spring-Boot:同时处理多个请求

在 spring-boot 中使用一个模板引擎渲染多个后缀