【spring boot】12.spring boot对多种不同类型数据库,多数据源配置使用

本文涉及的产品
RDS SQL Server Serverless,2-4RCU 50GB 3个月
推荐场景:
云数据库 RDS SQL Server,基础系列 2核4GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
简介: 2天时间,终于把spring boot下配置连接多种不同类型数据库,配置多数据源实现!======================================================================================================spr...

2天时间,终于把spring boot下配置连接多种不同类型数据库,配置多数据源实现!

======================================================================================================

spring boot对多种不同类型数据库,多数据源配置使用

多数据源配置相关官方API:https://docs.spring.io/spring-boot/docs/current/api/

环境如下:

  开发环境IDE:IntelliJ IDEA

  spring boot版本:1.5.9

  hibernate版本:5.0.12

  多数据源: sql server2008 和 mysql 5.5

 ======================================================================================================

 实现多数据源的配置连接,主要思路如下:

1》首先在application.properties中配置两个数据源  和必要的JPA相关配置

2》DataSourceConfig总装载类,分别声明多个数据源【并指定其中一个数据源为主数据源】

3》分别创建多个数据源的具体装载类,例如MyagenDataSourceConfig,并在具体装载类中,注入并完善JpaProperties,声明并引用实体管理事务管理,并在过程中指定了本数据源要作用的包的范围

4》根据第3步中指定的包,分别对应多个数据源的具体装载类,创建包结构,以及生成实体和对应的repository层操作

5》最后再controller层,依次调用各种数据源对应的各个包下的各种repository操作进行操作

 

那么主要实现目录如下:

 

======================================================================================================

下面依照思路,一步一步看实现:

1》首先在application.properties中配置两个数据源  和必要的JPA相关配置

完整代码:

application.properties

#datasource
myagen.spring.datasource.url=jdbc:sqlserver://localhost:1433;databasename=geneShop
myagen.spring.datasource.username=sa
myagen.spring.datasource.password=398023
myagen.spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver


orderdiscount.spring.datasource.url=jdbc:mysql://localhost:3306/orderdiscount
orderdiscount.spring.datasource.username=root
orderdiscount.spring.datasource.password=root
orderdiscount.spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#jpa 需要单独提出来
spring.jpa.show-sql=true

1.这个实现的例子中。使用的多数据源是不同数据库类型下的多数据源。

2.然后仅需要在application.properties中配置spring.datasource下的必要属性,当然,除了这4个必要属性之外,还有很多关于spring.datasource的配置,具体可以查看,spring boot官方完整文档:http://www.cnblogs.com/sxdcgaq8080/p/7724506.html,进入搜索【spring.datasource】,就可以找到完整的关于它的配置属性名。

3.这里分别对多数据源前面的属性命名分别添加了标识用于标识不同的数据源。例如:

myagen.spring.datasource.url 和  orderdiscount.spring.datasource.url

具体这个标识怎么用,就是用于在第二步中取前缀分别装载不同数据源的时候用。需要明白一点:application.properties文件中定义键名为什么都不会报错,但是如果不符合规范且你自己没有去处理,那你配置的键值对并不会被加载而起作用。

4.再说spring.jpa.show-sql,这个属性名不会因为在不同数据库下就不起作用了,所以,直接配置在这里即可。

5.最后要说的是hibernate.dialect,方言等等和不同类型数据库有关联的属性值,不能配置在配置文件中,因为没办法解析,所以这个要放在第3步中处理,如果需要查看这个,可以直接跳到第三步

 

===================================================================================================================================

2》DataSourceConfig总装载类,分别声明多个数据源【并指定其中一个数据源为主数据源】

1.这个DataSourceConfig总的装载类,就是根据上面配置文件中不同的前缀获取到不同的几个键值对的值,封装进了DataSource数据源,例如前缀:

myagen.spring.datasource

2.需要注意的是这个类需要@Configuration注解标注本类需要被扫描到

3.在有多个数据源的情况下,必须要指定其中一个为主数据源,通过

@Primary

完整代码:

DataSourceConfig.java
package com.agen.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
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;

/**
 * @author SXD
 * @date 2017/12/04
 * 多数据源装载配置类
 * 数据源的声明
 */
@Configuration
public class DataSourceConfig {

    /**
     * @return  我的基因网数据库
     */
    @Bean(name = "myagenDataSource")
    @Qualifier(value = "myagenDataSource")  //spring装配bean的唯一标识
    @ConfigurationProperties(prefix = "myagen.spring.datasource")   //application.properties配置文件中该数据源的配置前缀
    public DataSource myagenDataSource(){
        return DataSourceBuilder.create().build();
    }

    /**
     * @return   基因网订单返现数据库
     */
    @Primary    //配置该数据源为主数据源
    @Bean(name = "orderDiscountDataSource")
    @Qualifier(value = "orderDiscountDataSource")
    @ConfigurationProperties(prefix = "orderdiscount.spring.datasource")
    public DataSource orderDiscountDataSource(){
        return DataSourceBuilder.create().build();
    }
}
View Code

=============================================================================================================================================== 

 3》分别创建多个数据源的具体装载类,例如MyagenDataSourceConfig,并在具体装载类中,注入并完善JpaProperties,声明并引用实体管理事务管理,并在过程中指定了本数据源要作用的包的范围

 

主数据源完整代码:

OrderDiscountDataSourceConfig.java
package com.agen.config.datasource;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

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

/**
 * @author SXD
 * @date 2017/12/04
 * mysql数据库中数据源的 声明装载类
 *
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryOrderDiscount",   //EntityManagerFactory引用
                        transactionManagerRef = "transactionManagerOrderDiscount",      //transactionManager引用
                        basePackages = {"com.agen.orderdiscount"})                      //设置 基因网orderDiscountDataSource应用到的包
public class OrderDiscountDataSourceConfig {

    /**
     * 注入 基因网订单折扣数据源
     */
    @Autowired()
    @Qualifier("orderDiscountDataSource")
    private DataSource orderDiscountDataSource;

    /**
     * 注入JPA配置实体
     */
    @Autowired
    private JpaProperties jpaProperties;

    /**
     * 通过调用JPA配置实体中的解析方法,解析datasource中各属性的值
     * @param dataSource    数据源
     * @return     本数据源中各参数
     * Map中设值分别为:
     *      hibernate-dialect   方言
     *      hibernate.hbm2ddl.auto  DDL执行策略
     *      hibernate.physical_naming_strategy  命名策略
     *
     *这些和不同类型数据库密切相关的属性设置,不能设置在application.properties中,所以需要再不同的数据源中具体设置,赋值给JpaProperties
     */
    private Map<String,String> getVendorProperties(DataSource dataSource){
        jpaProperties.setDatabase(Database.MYSQL);
        Map<String,String> map = new HashMap<>();
        map.put("hibernate.dialect","org.hibernate.dialect.MySQL5Dialect");
        map.put("hibernate.hbm2ddl.auto","update");
        map.put("hibernate.physical_naming_strategy","org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl");
        jpaProperties.setProperties(map);
        return  jpaProperties.getHibernateProperties(dataSource);
    }

    /**
     * 配置EntityManagerFactory实体
     * @param builder
     * @return      实体管理工厂
     * packages     扫描@Entity注释的软件包名称
     * persistenceUnit  持久性单元的名称。 如果只建立一个EntityManagerFactory,你可以省略这个,但是如果在同一个应用程序中有多个,你应该给它们不同的名字
     * properties       标准JPA或供应商特定配置的通用属性。 这些属性覆盖构造函数中提供的任何值。
     *
     */
    @Primary
    @Bean(name = "entityManagerFactoryOrderDiscount")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryOrderDiscount(EntityManagerFactoryBuilder builder){
        return builder
                .dataSource(orderDiscountDataSource)
                .properties(getVendorProperties(orderDiscountDataSource))
                .packages(new String[]{"com.agen.orderdiscount"})
                .persistenceUnit("orderDiscountPersistenceUnit")
                .build();
    }

    /**
     * 配置EntityManager实体
     * @param builder
     * @return      实体管理器
     */
    @Primary
    @Bean(name = "entityManagerOrderDiscount")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder){
        return entityManagerFactoryOrderDiscount(builder).getObject().createEntityManager();
    }


    /**
     * 配置事务transactionManager
     * @param builder
     * @return      事务管理器
     */
    @Primary
    @Bean(name = "transactionManagerOrderDiscount")
    public PlatformTransactionManager transactionManagerOrderDiscount(EntityManagerFactoryBuilder builder){
        return  new JpaTransactionManager(entityManagerFactoryOrderDiscount(builder).getObject());
    }



}
View Code

 

其他数据源完整代码:

MyagenDataSourceConfig.java
package com.agen.config.datasource;

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.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

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

/**
 * @author SXD
 * @date 2017/12/04
 * sql server数据库中数据源的 声明装载类
 *
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryMyagen",   //实体管理引用
        transactionManagerRef = "transactionManagerMyagen",                     //事务管理引用
        basePackages = {"com.agen.myagen"})                                    //设置 myagenDataSource应用到的包
public class MyagenDataSourceConfig {

    /**
     * 注入 我的基因网数据源
     */
    @Autowired()
    @Qualifier("myagenDataSource")
    private DataSource myagenDataSource;

    /**
     * 注入JPA配置实体
     */
    @Autowired
    private JpaProperties jpaProperties;

    /**
     * 通过调用JPA配置实体中的解析方法,解析datasource中各属性的值
     * @param dataSource    数据源
     * @return     本数据源中各参数
     * Map中设值分别为:
     *      hibernate-dialect   方言
     *      hibernate.hbm2ddl.auto  DDL执行策略
     *      hibernate.physical_naming_strategy  命名策略
     *
     *这些和不同类型数据库密切相关的属性设置,不能设置在application.properties中,所以需要再不同的数据源中具体设置,赋值给JpaProperties
     */
    private Map<String, String> getVendorProperties(DataSource dataSource) {
        jpaProperties.setDatabase(Database.SQL_SERVER);
        Map<String,String> map = new HashMap<>();
        map.put("hibernate.dialect","org.hibernate.dialect.SQLServer2008Dialect");
        map.put("hibernate.hbm2ddl.auto","update");
        map.put("hibernate.physical_naming_strategy","org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl");
        jpaProperties.setProperties(map);
        return jpaProperties.getHibernateProperties(dataSource);
    }

    /**
     * 配置EntityManagerFactory实体
     *
     * @param builder
     * @return
     * packages     扫描@Entity注释的软件包名称
     * persistenceUnit  持久性单元的名称。 如果只建立一个EntityManagerFactory,你可以省略这个,但是如果在同一个应用程序中有多个,你应该给它们不同的名字
     * properties       标准JPA或供应商特定配置的通用属性。 这些属性覆盖构造函数中提供的任何值。
     */
    @Bean(name = "entityManagerFactoryMyagen")
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryMyagen(EntityManagerFactoryBuilder builder) {
        return builder
                .dataSource(myagenDataSource)
                .properties(getVendorProperties(myagenDataSource))
                .packages(new String[]{"com.agen.myagen"})
                .persistenceUnit("myagenPersistenceUnit")
                .build();
    }

    /**
     * 配置EntityManager实体
     *
     * @param builder
     * @return 实体管理器
     */
    @Bean(name = "entityManagerMyagen")
    public EntityManager entityManager(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryMyagen(builder).getObject().createEntityManager();
    }


    /**
     * 配置事务
     *
     * @param builder
     * @return 事务管理器
     */
    @Bean(name = "transactionManagerMyagen")
    public PlatformTransactionManager transactionManagerMyagen(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryMyagen(builder).getObject());
    }

}
View Code

 

 1.主数据源和其他数据源最大的区别在于,主数据源中 的实体管理器,实体工厂管理器,事务管理器在声明加载时 ,要声明自己是主数据源的,通过

@Primary

 2.在实体工厂管理器中,需要设置

persistenceUnit

 如果仅有一个数据源的话,不需要设置这个,但是多数据源的情况下,需要设置其为不同的值即可,没有具体的命名规则。

3.指定本数据源要扫描的包名,可以指定多个包,也可以将entity和repository放在同一个包下,这样仅需要指定一个即可被扫描到。

4.关于application.properties中有关和数据库操作相关的部分属性值的默认值是什么设置的:

 

查看JpaProperties源码,默认的为hibernate命名生成策略:

而这种命名生成策略是为若有驼峰命名出现orderId,则数据库中会有order_id下划线出现。我自己不想采用这种。

 DDL策略:

 

 =================================================================================================================================================================

4》根据第3步中指定的包,分别对应多个数据源的具体装载类,创建包结构,以及生成实体和对应的repository层操作

 

XxOrder.java

package com.agen.myagen.entity;

import javax.persistence.*;
import java.math.BigDecimal;
import java.sql.Timestamp;

@Entity
@Table(name = "xx_order", schema = "dbo", catalog = "geneshop")
public class XxOrder {
    private int id;
    private Timestamp createDate;
    private Timestamp modifyDate;
    private String address;
    private BigDecimal amountPaid;
    private String areaName;
    private String consignee;
    private BigDecimal couponDiscount;
    private int exchangePoint;
    private Timestamp expire;
    private BigDecimal fee;
    private BigDecimal freight;
    private String invoiceTitle;
    private boolean isAllocatedStock;
    private boolean isInvoice;
    private Timestamp lockExpire;
    private String memo;
    private String name;
    private BigDecimal offsetAmount;
    private int orderStatus;
    private String paymentMethodName;
    private int paymentStatus;
    private String phone;
    private BigDecimal promotionDiscount;
    private String promotionName;
    private int rewardPoint;
    private String shippingMethodName;
    private int shippingStatus;
    private String sn;
    private BigDecimal tax;
    private int type;
    private String zipCode;
    private String memberorderno;
    private Integer ordertype;
    private Boolean distributeState;
    private Timestamp ctime;
    private String guid;
    private String cbqrr;
    private Timestamp cbqrTime;
    private Boolean isCbqr;
    private Boolean isSrqr;
    private String srqrr;
    private Timestamp srqrTime;
    private String isShow;
    private Boolean isHunantb;
    private Boolean byCreditCard;
    private XxMember xxMemberByMember;
    private XxAdmin xxAdminByOperator;
    private XxAdmin xxAdminByAdmin;


    @Id
    @Column(name = "id", nullable = false, precision = 0)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "create_date", nullable = false)
    public Timestamp getCreateDate() {
        return createDate;
    }

    public void setCreateDate(Timestamp createDate) {
        this.createDate = createDate;
    }

    @Basic
    @Column(name = "modify_date", nullable = false)
    public Timestamp getModifyDate() {
        return modifyDate;
    }

    public void setModifyDate(Timestamp modifyDate) {
        this.modifyDate = modifyDate;
    }

    @Basic
    @Column(name = "address", nullable = false, length = 255)
    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Basic
    @Column(name = "amount_paid", nullable = false, precision = 6)
    public BigDecimal getAmountPaid() {
        return amountPaid;
    }

    public void setAmountPaid(BigDecimal amountPaid) {
        this.amountPaid = amountPaid;
    }

    @Basic
    @Column(name = "area_name", nullable = false, length = 255)
    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    @Basic
    @Column(name = "consignee", nullable = false, length = 255)
    public String getConsignee() {
        return consignee;
    }

    public void setConsignee(String consignee) {
        this.consignee = consignee;
    }

    @Basic
    @Column(name = "coupon_discount", nullable = false, precision = 6)
    public BigDecimal getCouponDiscount() {
        return couponDiscount;
    }

    public void setCouponDiscount(BigDecimal couponDiscount) {
        this.couponDiscount = couponDiscount;
    }

    @Basic
    @Column(name = "exchange_point", nullable = false, precision = 0)
    public int getExchangePoint() {
        return exchangePoint;
    }

    public void setExchangePoint(int exchangePoint) {
        this.exchangePoint = exchangePoint;
    }

    @Basic
    @Column(name = "expire", nullable = true)
    public Timestamp getExpire() {
        return expire;
    }

    public void setExpire(Timestamp expire) {
        this.expire = expire;
    }

    @Basic
    @Column(name = "fee", nullable = false, precision = 6)
    public BigDecimal getFee() {
        return fee;
    }

    public void setFee(BigDecimal fee) {
        this.fee = fee;
    }

    @Basic
    @Column(name = "freight", nullable = false, precision = 6)
    public BigDecimal getFreight() {
        return freight;
    }

    public void setFreight(BigDecimal freight) {
        this.freight = freight;
    }

    @Basic
    @Column(name = "invoice_title", nullable = true, length = 255)
    public String getInvoiceTitle() {
        return invoiceTitle;
    }

    public void setInvoiceTitle(String invoiceTitle) {
        this.invoiceTitle = invoiceTitle;
    }

    @Basic
    @Column(name = "is_allocated_stock", nullable = false)
    public boolean isAllocatedStock() {
        return isAllocatedStock;
    }

    public void setAllocatedStock(boolean allocatedStock) {
        isAllocatedStock = allocatedStock;
    }

    @Basic
    @Column(name = "is_invoice", nullable = false)
    public boolean isInvoice() {
        return isInvoice;
    }

    public void setInvoice(boolean invoice) {
        isInvoice = invoice;
    }

    @Basic
    @Column(name = "lock_expire", nullable = true)
    public Timestamp getLockExpire() {
        return lockExpire;
    }

    public void setLockExpire(Timestamp lockExpire) {
        this.lockExpire = lockExpire;
    }

    @Basic
    @Column(name = "memo", nullable = true, length = 255)
    public String getMemo() {
        return memo;
    }

    public void setMemo(String memo) {
        this.memo = memo;
    }

    @Basic
    @Column(name = "name", nullable = false, length = 500)
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Basic
    @Column(name = "offset_amount", nullable = false, precision = 6)
    public BigDecimal getOffsetAmount() {
        return offsetAmount;
    }

    public void setOffsetAmount(BigDecimal offsetAmount) {
        this.offsetAmount = offsetAmount;
    }

    @Basic
    @Column(name = "order_status", nullable = false)
    public int getOrderStatus() {
        return orderStatus;
    }

    public void setOrderStatus(int orderStatus) {
        this.orderStatus = orderStatus;
    }

    @Basic
    @Column(name = "payment_method_name", nullable = true, length = 255)
    public String getPaymentMethodName() {
        return paymentMethodName;
    }

    public void setPaymentMethodName(String paymentMethodName) {
        this.paymentMethodName = paymentMethodName;
    }

    @Basic
    @Column(name = "payment_status", nullable = false)
    public int getPaymentStatus() {
        return paymentStatus;
    }

    public void setPaymentStatus(int paymentStatus) {
        this.paymentStatus = paymentStatus;
    }

    @Basic
    @Column(name = "phone", nullable = false, length = 255)
    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Basic
    @Column(name = "promotion_discount", nullable = false, precision = 6)
    public BigDecimal getPromotionDiscount() {
        return promotionDiscount;
    }

    public void setPromotionDiscount(BigDecimal promotionDiscount) {
        this.promotionDiscount = promotionDiscount;
    }

    @Basic
    @Column(name = "promotion_name", nullable = true, length = 255)
    public String getPromotionName() {
        return promotionName;
    }

    public void setPromotionName(String promotionName) {
        this.promotionName = promotionName;
    }

    @Basic
    @Column(name = "reward_point", nullable = false, precision = 0)
    public int getRewardPoint() {
        return rewardPoint;
    }

    public void setRewardPoint(int rewardPoint) {
        this.rewardPoint = rewardPoint;
    }

    @Basic
    @Column(name = "shipping_method_name", nullable = true, length = 255)
    public String getShippingMethodName() {
        return shippingMethodName;
    }

    public void setShippingMethodName(String shippingMethodName) {
        this.shippingMethodName = shippingMethodName;
    }

    @Basic
    @Column(name = "shipping_status", nullable = false)
    public int getShippingStatus() {
        return shippingStatus;
    }

    public void setShippingStatus(int shippingStatus) {
        this.shippingStatus = shippingStatus;
    }

    @Basic
    @Column(name = "sn", nullable = false, length = 100)
    public String getSn() {
        return sn;
    }

    public void setSn(String sn) {
        this.sn = sn;
    }

    @Basic
    @Column(name = "tax", nullable = false, precision = 6)
    public BigDecimal getTax() {
        return tax;
    }

    public void setTax(BigDecimal tax) {
        this.tax = tax;
    }

    @Basic
    @Column(name = "type", nullable = false)
    public int getType() {
        return type;
    }

    public void setType(int type) {
        this.type = type;
    }

    @Basic
    @Column(name = "zip_code", nullable = false, length = 255)
    public String getZipCode() {
        return zipCode;
    }

    public void setZipCode(String zipCode) {
        this.zipCode = zipCode;
    }

    @Basic
    @Column(name = "memberorderno", nullable = true, length = 255)
    public String getMemberorderno() {
        return memberorderno;
    }

    public void setMemberorderno(String memberorderno) {
        this.memberorderno = memberorderno;
    }

    @Basic
    @Column(name = "ordertype", nullable = true)
    public Integer getOrdertype() {
        return ordertype;
    }

    public void setOrdertype(Integer ordertype) {
        this.ordertype = ordertype;
    }

    @Basic
    @Column(name = "distributeState", nullable = true)
    public Boolean getDistributeState() {
        return distributeState;
    }

    public void setDistributeState(Boolean distributeState) {
        this.distributeState = distributeState;
    }

    @Basic
    @Column(name = "ctime", nullable = true)
    public Timestamp getCtime() {
        return ctime;
    }

    public void setCtime(Timestamp ctime) {
        this.ctime = ctime;
    }

    @Basic
    @Column(name = "guid", nullable = true, length = 255)
    public String getGuid() {
        return guid;
    }

    public void setGuid(String guid) {
        this.guid = guid;
    }

    @Basic
    @Column(name = "cbqrr", nullable = true, length = 255)
    public String getCbqrr() {
        return cbqrr;
    }

    public void setCbqrr(String cbqrr) {
        this.cbqrr = cbqrr;
    }

    @Basic
    @Column(name = "cbqr_time", nullable = true)
    public Timestamp getCbqrTime() {
        return cbqrTime;
    }

    public void setCbqrTime(Timestamp cbqrTime) {
        this.cbqrTime = cbqrTime;
    }

    @Basic
    @Column(name = "is_cbqr", nullable = true)
    public Boolean getCbqr() {
        return isCbqr;
    }

    public void setCbqr(Boolean cbqr) {
        isCbqr = cbqr;
    }

    @Basic
    @Column(name = "is_srqr", nullable = true)
    public Boolean getSrqr() {
        return isSrqr;
    }

    public void setSrqr(Boolean srqr) {
        isSrqr = srqr;
    }

    @Basic
    @Column(name = "srqrr", nullable = true, length = 255)
    public String getSrqrr() {
        return srqrr;
    }

    public void setSrqrr(String srqrr) {
        this.srqrr = srqrr;
    }

    @Basic
    @Column(name = "srqr_time", nullable = true)
    public Timestamp getSrqrTime() {
        return srqrTime;
    }

    public void setSrqrTime(Timestamp srqrTime) {
        this.srqrTime = srqrTime;
    }

    @Basic
    @Column(name = "is_show", nullable = true, length = 255)
    public String getIsShow() {
        return isShow;
    }

    public void setIsShow(String isShow) {
        this.isShow = isShow;
    }

    @Basic
    @Column(name = "is_hunantb", nullable = true)
    public Boolean getHunantb() {
        return isHunantb;
    }

    public void setHunantb(Boolean hunantb) {
        isHunantb = hunantb;
    }

    @Basic
    @Column(name = "by_credit_card", nullable = true)
    public Boolean getByCreditCard() {
        return byCreditCard;
    }

    public void setByCreditCard(Boolean byCreditCard) {
        this.byCreditCard = byCreditCard;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        XxOrder xxOrder = (XxOrder) o;

        if (id != xxOrder.id) return false;
        if (exchangePoint != xxOrder.exchangePoint) return false;
        if (isAllocatedStock != xxOrder.isAllocatedStock) return false;
        if (isInvoice != xxOrder.isInvoice) return false;
        if (orderStatus != xxOrder.orderStatus) return false;
        if (paymentStatus != xxOrder.paymentStatus) return false;
        if (rewardPoint != xxOrder.rewardPoint) return false;
        if (shippingStatus != xxOrder.shippingStatus) return false;
        if (type != xxOrder.type) return false;
        if (createDate != null ? !createDate.equals(xxOrder.createDate) : xxOrder.createDate != null) return false;
        if (modifyDate != null ? !modifyDate.equals(xxOrder.modifyDate) : xxOrder.modifyDate != null) return false;
        if (address != null ? !address.equals(xxOrder.address) : xxOrder.address != null) return false;
        if (amountPaid != null ? !amountPaid.equals(xxOrder.amountPaid) : xxOrder.amountPaid != null) return false;
        if (areaName != null ? !areaName.equals(xxOrder.areaName) : xxOrder.areaName != null) return false;
        if (consignee != null ? !consignee.equals(xxOrder.consignee) : xxOrder.consignee != null) return false;
        if (couponDiscount != null ? !couponDiscount.equals(xxOrder.couponDiscount) : xxOrder.couponDiscount != null)
            return false;
        if (expire != null ? !expire.equals(xxOrder.expire) : xxOrder.expire != null) return false;
        if (fee != null ? !fee.equals(xxOrder.fee) : xxOrder.fee != null) return false;
        if (freight != null ? !freight.equals(xxOrder.freight) : xxOrder.freight != null) return false;
        if (invoiceTitle != null ? !invoiceTitle.equals(xxOrder.invoiceTitle) : xxOrder.invoiceTitle != null)
            return false;
        if (lockExpire != null ? !lockExpire.equals(xxOrder.lockExpire) : xxOrder.lockExpire != null) return false;
        if (memo != null ? !memo.equals(xxOrder.memo) : xxOrder.memo != null) return false;
        if (name != null ? !name.equals(xxOrder.name) : xxOrder.name != null) return false;
        if (offsetAmount != null ? !offsetAmount.equals(xxOrder.offsetAmount) : xxOrder.offsetAmount != null)
            return false;
        if (paymentMethodName != null ? !paymentMethodName.equals(xxOrder.paymentMethodName) : xxOrder.paymentMethodName != null)
            return false;
        if (phone != null ? !phone.equals(xxOrder.phone) : xxOrder.phone != null) return false;
        if (promotionDiscount != null ? !promotionDiscount.equals(xxOrder.promotionDiscount) : xxOrder.promotionDiscount != null)
            return false;
        if (promotionName != null ? !promotionName.equals(xxOrder.promotionName) : xxOrder.promotionName != null)
            return false;
        if (shippingMethodName != null ? !shippingMethodName.equals(xxOrder.shippingMethodName) : xxOrder.shippingMethodName != null)
            return false;
        if (sn != null ? !sn.equals(xxOrder.sn) : xxOrder.sn != null) return false;
        if (tax != null ? !tax.equals(xxOrder.tax) : xxOrder.tax != null) return false;
        if (zipCode != null ? !zipCode.equals(xxOrder.zipCode) : xxOrder.zipCode != null) return false;
        if (memberorderno != null ? !memberorderno.equals(xxOrder.memberorderno) : xxOrder.memberorderno != null)
            return false;
        if (ordertype != null ? !ordertype.equals(xxOrder.ordertype) : xxOrder.ordertype != null) return false;
        if (distributeState != null ? !distributeState.equals(xxOrder.distributeState) : xxOrder.distributeState != null)
            return false;
        if (ctime != null ? !ctime.equals(xxOrder.ctime) : xxOrder.ctime != null) return false;
        if (guid != null ? !guid.equals(xxOrder.guid) : xxOrder.guid != null) return false;
        if (cbqrr != null ? !cbqrr.equals(xxOrder.cbqrr) : xxOrder.cbqrr != null) return false;
        if (cbqrTime != null ? !cbqrTime.equals(xxOrder.cbqrTime) : xxOrder.cbqrTime != null) return false;
        if (isCbqr != null ? !isCbqr.equals(xxOrder.isCbqr) : xxOrder.isCbqr != null) return false;
        if (isSrqr != null ? !isSrqr.equals(xxOrder.isSrqr) : xxOrder.isSrqr != null) return false;
        if (srqrr != null ? !srqrr.equals(xxOrder.srqrr) : xxOrder.srqrr != null) return false;
        if (srqrTime != null ? !srqrTime.equals(xxOrder.srqrTime) : xxOrder.srqrTime != null) return false;
        if (isShow != null ? !isShow.equals(xxOrder.isShow) : xxOrder.isShow != null) return false;
        if (isHunantb != null ? !isHunantb.equals(xxOrder.isHunantb) : xxOrder.isHunantb != null) return false;
        if (byCreditCard != null ? !byCreditCard.equals(xxOrder.byCreditCard) : xxOrder.byCreditCard != null)
            return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (createDate != null ? createDate.hashCode() : 0);
        result = 31 * result + (modifyDate != null ? modifyDate.hashCode() : 0);
        result = 31 * result + (address != null ? address.hashCode() : 0);
        result = 31 * result + (amountPaid != null ? amountPaid.hashCode() : 0);
        result = 31 * result + (areaName != null ? areaName.hashCode() : 0);
        result = 31 * result + (consignee != null ? consignee.hashCode() : 0);
        result = 31 * result + (couponDiscount != null ? couponDiscount.hashCode() : 0);
        result = 31 * result + exchangePoint;
        result = 31 * result + (expire != null ? expire.hashCode() : 0);
        result = 31 * result + (fee != null ? fee.hashCode() : 0);
        result = 31 * result + (freight != null ? freight.hashCode() : 0);
        result = 31 * result + (invoiceTitle != null ? invoiceTitle.hashCode() : 0);
        result = 31 * result + (isAllocatedStock ? 1 : 0);
        result = 31 * result + (isInvoice ? 1 : 0);
        result = 31 * result + (lockExpire != null ? lockExpire.hashCode() : 0);
        result = 31 * result + (memo != null ? memo.hashCode() : 0);
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (offsetAmount != null ? offsetAmount.hashCode() : 0);
        result = 31 * result + orderStatus;
        result = 31 * result + (paymentMethodName != null ? paymentMethodName.hashCode() : 0);
        result = 31 * result + paymentStatus;
        result = 31 * result + (phone != null ? phone.hashCode() : 0);
        result = 31 * result + (promotionDiscount != null ? promotionDiscount.hashCode() : 0);
        result = 31 * result + (promotionName != null ? promotionName.hashCode() : 0);
        result = 31 * result + rewardPoint;
        result = 31 * result + (shippingMethodName != null ? shippingMethodName.hashCode() : 0);
        result = 31 * result + shippingStatus;
        result = 31 * result + (sn != null ? sn.hashCode() : 0);
        result = 31 * result + (tax != null ? tax.hashCode() : 0);
        result = 31 * result + type;
        result = 31 * result + (zipCode != null ? zipCode.hashCode() : 0);
        result = 31 * result + (memberorderno != null ? memberorderno.hashCode() : 0);
        result = 31 * result + (ordertype != null ? ordertype.hashCode() : 0);
        result = 31 * result + (distributeState != null ? distributeState.hashCode() : 0);
        result = 31 * result + (ctime != null ? ctime.hashCode() : 0);
        result = 31 * result + (guid != null ? guid.hashCode() : 0);
        result = 31 * result + (cbqrr != null ? cbqrr.hashCode() : 0);
        result = 31 * result + (cbqrTime != null ? cbqrTime.hashCode() : 0);
        result = 31 * result + (isCbqr != null ? isCbqr.hashCode() : 0);
        result = 31 * result + (isSrqr != null ? isSrqr.hashCode() : 0);
        result = 31 * result + (srqrr != null ? srqrr.hashCode() : 0);
        result = 31 * result + (srqrTime != null ? srqrTime.hashCode() : 0);
        result = 31 * result + (isShow != null ? isShow.hashCode() : 0);
        result = 31 * result + (isHunantb != null ? isHunantb.hashCode() : 0);
        result = 31 * result + (byCreditCard != null ? byCreditCard.hashCode() : 0);
        return result;
    }

    @ManyToOne
    @JoinColumn(name = "member", referencedColumnName = "id", nullable = false)
    public XxMember getXxMemberByMember() {
        return xxMemberByMember;
    }

    public void setXxMemberByMember(XxMember xxMemberByMember) {
        this.xxMemberByMember = xxMemberByMember;
    }


    @ManyToOne
    @JoinColumn(name = "operator", referencedColumnName = "id")
    public XxAdmin getXxAdminByOperator() {
        return xxAdminByOperator;
    }

    public void setXxAdminByOperator(XxAdmin xxAdminByOperator) {
        this.xxAdminByOperator = xxAdminByOperator;
    }


    @ManyToOne
    @JoinColumn(name = "admin", referencedColumnName = "id")
    public XxAdmin getXxAdminByAdmin() {
        return xxAdminByAdmin;
    }

    public void setXxAdminByAdmin(XxAdmin xxAdminByAdmin) {
        this.xxAdminByAdmin = xxAdminByAdmin;
    }


}
View Code

OrderRepository.java

package com.agen.myagen.repository;

import com.agen.myagen.entity.XxAdmin;
import com.agen.myagen.entity.XxOrder;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface OrderRepository  extends JpaRepository<XxOrder,Integer> {

    List<XxOrder> findTop10ByXxAdminByOperator(XxAdmin xxAdminByOperator);

    @Override
    XxOrder findOne(Integer integer);
}
View Code

Member.java

package com.agen.orderdiscount.entity;

import lombok.*;
import lombok.experimental.Accessors;

import org.hibernate.annotations.GenericGenerator;

import javax.persistence.*;


@Data(staticConstructor = "of")
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Entity
@GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator" )
public class Member {


    @Id
    @GeneratedValue(generator = "uuid2")
    private String memberId;


    @Column(nullable = false)
    @NonNull
    private Integer memberGrade;

    @Column(nullable = false)
    @NonNull
    private String orderSn;
}
View Code

MemberRepositpry.java

package com.agen.orderdiscount.repository;

import com.agen.orderdiscount.entity.Member;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface MemberRepository  extends JpaRepository<Member,String>{
    @Override
    Member save(Member member);

    List<Member> findByMemberGrade(Integer memberGrade);
}
View Code

 

1.我这里myagen数据源下数据库中表早已存在,是根据hibernate反转工具生成的几个需要的类

【hibernate反转工具怎么使用】

idea下的实体生成反转工具:http://www.cnblogs.com/sxdcgaq8080/p/7978334.html

myecplise下的实体生成反转工具:http://www.cnblogs.com/sxdcgaq8080/p/5593591.html

 2.和数据库打交道的持久化框架是spring boot自带的spring-data-jpa。

【spring-data-jpa怎么使用】

入门使用:http://www.cnblogs.com/sxdcgaq8080/p/7890571.html

复杂使用:http://www.cnblogs.com/sxdcgaq8080/p/7894828.html

 3.Member实体中使用了lombok,一个java的一个奇技淫巧

lombok的详解和使用:http://www.cnblogs.com/sxdcgaq8080/p/7884477.html

 4.关于Member.java实体,因为这个对应的是orderdiscount数据源,也就是主数据源,是mysql这边的,是先写了实体之后,自动根据第三步中设置在map中的

hibernate.physical_naming_strategy

 ,所以生成的数据表中的字段,应该是不带下划线的。

关于hibernate的命名规则,设置参考:http://www.cnblogs.com/sxdcgaq8080/p/7910474.html

 

=========================================================================================================================================

 5》最后再controller层,依次调用各种数据源对应的各个包下的各种repository操作进行操作

 

这一层,什么也不用多说了

MainController.java

package com.agen.controller;

import com.agen.myagen.entity.XxAdmin;
import com.agen.myagen.entity.XxOrder;
import com.agen.myagen.repository.OrderRepository;
import com.agen.orderdiscount.entity.Member;
import com.agen.orderdiscount.repository.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Controller
public class MainController {

    @Autowired
    private OrderRepository orderRepository;
    @Autowired
    private MemberRepository memberRepository;

    @RequestMapping("lo")
    public void getOrder(){
        XxOrder xxOrder = orderRepository.findOne(1510);
        System.out.println("sql server数据库查到order编号:"+xxOrder.getSn());
        Member member = new Member();
        member.setMemberId(UUID.randomUUID().toString());
        member.setMemberGrade(2);
        member.setOrderSn(xxOrder.getSn());

        Member member1 = memberRepository.save(member);
        if(Objects.nonNull(member1)){
            System.out.println("mysql数据库插入member成功");

            List<Member> list = memberRepository.findByMemberGrade(2);
            if(Objects.nonNull(list) && list.size() > 0){
                list.forEach(i->{
                    System.out.println("mysql数据库查出order编号:"+i.getOrderSn());
                });
            }
        }


    }
}
View Code

然后启动,启动可以看到下面这些信息:

 

最后,访问一下这个地址:

 

 可以看到和多数据源交互的 SQL语句打印出来:

 

 

======================================================================================================

好了 ,终于完成了!!!!

 

相关文章
|
4天前
|
Java 开发者 微服务
手写模拟Spring Boot自动配置功能
【11月更文挑战第19天】随着微服务架构的兴起,Spring Boot作为一种快速开发框架,因其简化了Spring应用的初始搭建和开发过程,受到了广大开发者的青睐。自动配置作为Spring Boot的核心特性之一,大大减少了手动配置的工作量,提高了开发效率。
20 0
|
7天前
|
Java 数据库连接
SpringBoot配置多数据源实战
第四届光学与机器视觉国际学术会议(ICOMV 2025) 2025 4th International Conference on Optics and Machine Vision
33 8
|
11天前
|
消息中间件 资源调度 关系型数据库
如何在Flink on YARN环境中配置Debezium CDC 3.0,以实现实时捕获数据库变更事件并将其传输到Flink进行处理
本文介绍了如何在Flink on YARN环境中配置Debezium CDC 3.0,以实现实时捕获数据库变更事件并将其传输到Flink进行处理。主要内容包括安装Debezium、配置Kafka Connect、创建Flink任务以及启动任务的具体步骤,为构建实时数据管道提供了详细指导。
33 9
|
11天前
|
安全 Nacos 数据库
Nacos是一款流行的微服务注册与配置中心,但直接暴露在公网中可能导致非法访问和数据库篡改
Nacos是一款流行的微服务注册与配置中心,但直接暴露在公网中可能导致非法访问和数据库篡改。本文详细探讨了这一问题的原因及解决方案,包括限制公网访问、使用HTTPS、强化数据库安全、启用访问控制、监控和审计等步骤,帮助开发者确保服务的安全运行。
24 3
|
14天前
|
Java Spring
[Spring]aop的配置与使用
本文介绍了AOP(面向切面编程)的基本概念和核心思想。AOP是Spring框架的核心功能之一,通过动态代理在不修改原代码的情况下注入新功能。文章详细解释了连接点、切入点、通知、切面等关键概念,并列举了前置通知、后置通知、最终通知、异常通知和环绕通知五种通知类型。
27 1
|
14天前
|
PHP 数据库 数据安全/隐私保护
布谷直播源码部署服务器关于数据库配置的详细说明
布谷直播系统源码搭建部署时数据库配置明细!
|
16天前
|
Java 数据库连接 数据库
如何构建高效稳定的Java数据库连接池,涵盖连接池配置、并发控制和异常处理等方面
本文介绍了如何构建高效稳定的Java数据库连接池,涵盖连接池配置、并发控制和异常处理等方面。通过合理配置初始连接数、最大连接数和空闲连接超时时间,确保系统性能和稳定性。文章还探讨了同步阻塞、异步回调和信号量等并发控制策略,并提供了异常处理的最佳实践。最后,给出了一个简单的连接池示例代码,并推荐使用成熟的连接池框架(如HikariCP、C3P0)以简化开发。
36 2
|
18天前
|
关系型数据库 MySQL Linux
在 CentOS 7 中通过编译源码方式安装 MySQL 数据库的详细步骤,包括准备工作、下载源码、编译安装、配置 MySQL 服务、登录设置等。
本文介绍了在 CentOS 7 中通过编译源码方式安装 MySQL 数据库的详细步骤,包括准备工作、下载源码、编译安装、配置 MySQL 服务、登录设置等。同时,文章还对比了编译源码安装与使用 RPM 包安装的优缺点,帮助读者根据需求选择最合适的方法。通过具体案例,展示了编译源码安装的灵活性和定制性。
59 2
|
5月前
|
druid Java 关系型数据库
在Spring Boot中集成Druid实现多数据源有两种常用的方式:使用Spring Boot的自动配置和手动配置。
在Spring Boot中集成Druid实现多数据源有两种常用的方式:使用Spring Boot的自动配置和手动配置。
789 5
|
4月前
|
存储 Java 关系型数据库
Spring Data与多数据源配置
Spring Data与多数据源配置

热门文章

最新文章