2天时间,终于把spring boot下配置连接多种不同类型数据库,配置多数据源实现!
======================================================================================================
spring boot对多种不同类型数据库,多数据源配置使用
环境如下:
开发环境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
packagecom.agen.config;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;importorg.springframework.boot.context.properties.ConfigurationProperties;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Primary;importjavax.sql.DataSource;/***@authorSXD
* @date 2017/12/04
* 多数据源装载配置类
* 数据源的声明*/@Configurationpublic classDataSourceConfig {/***@return我的基因网数据库*/@Bean(name= "myagenDataSource")
@Qualifier(value= "myagenDataSource") //spring装配bean的唯一标识
@ConfigurationProperties(prefix = "myagen.spring.datasource") //application.properties配置文件中该数据源的配置前缀
publicDataSource myagenDataSource(){returnDataSourceBuilder.create().build();
}/***@return基因网订单返现数据库*/@Primary//配置该数据源为主数据源
@Bean(name = "orderDiscountDataSource")
@Qualifier(value= "orderDiscountDataSource")
@ConfigurationProperties(prefix= "orderdiscount.spring.datasource")publicDataSource orderDiscountDataSource(){returnDataSourceBuilder.create().build();
}
}
View Code
===============================================================================================================================================
3》分别创建多个数据源的具体装载类,例如MyagenDataSourceConfig,并在具体装载类中,注入并完善JpaProperties,声明并引用实体管理和事务管理,并在过程中指定了本数据源要作用的包的范围
主数据源完整代码:
OrderDiscountDataSourceConfig.java
packagecom.agen.config.datasource;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.boot.autoconfigure.orm.jpa.JpaProperties;importorg.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.context.annotation.Primary;importorg.springframework.data.jpa.repository.config.EnableJpaRepositories;importorg.springframework.orm.jpa.JpaTransactionManager;importorg.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;importorg.springframework.orm.jpa.vendor.Database;importorg.springframework.transaction.PlatformTransactionManager;importorg.springframework.transaction.annotation.EnableTransactionManagement;importjavax.persistence.EntityManager;importjavax.sql.DataSource;importjava.util.HashMap;importjava.util.Map;/***@authorSXD
* @date 2017/12/04
* mysql数据库中数据源的 声明装载类
**/@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef= "entityManagerFactoryOrderDiscount", //EntityManagerFactory引用
transactionManagerRef = "transactionManagerOrderDiscount", //transactionManager引用
basePackages = {"com.agen.orderdiscount"}) //设置 基因网orderDiscountDataSource应用到的包
public classOrderDiscountDataSourceConfig {/*** 注入 基因网订单折扣数据源*/@Autowired()
@Qualifier("orderDiscountDataSource")privateDataSource orderDiscountDataSource;/*** 注入JPA配置实体*/@AutowiredprivateJpaProperties jpaProperties;/*** 通过调用JPA配置实体中的解析方法,解析datasource中各属性的值
*@paramdataSource 数据源
*@return本数据源中各参数
* Map中设值分别为:
* hibernate-dialect 方言
* hibernate.hbm2ddl.auto DDL执行策略
* hibernate.physical_naming_strategy 命名策略
*
*这些和不同类型数据库密切相关的属性设置,不能设置在application.properties中,所以需要再不同的数据源中具体设置,赋值给JpaProperties*/
private MapgetVendorProperties(DataSource dataSource){
jpaProperties.setDatabase(Database.MYSQL);
Map 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);returnjpaProperties.getHibernateProperties(dataSource);
}/*** 配置EntityManagerFactory实体
*@parambuilder
*@return实体管理工厂
* packages 扫描@Entity注释的软件包名称
* persistenceUnit 持久性单元的名称。 如果只建立一个EntityManagerFactory,你可以省略这个,但是如果在同一个应用程序中有多个,你应该给它们不同的名字
* properties 标准JPA或供应商特定配置的通用属性。 这些属性覆盖构造函数中提供的任何值。
**/@Primary
@Bean(name= "entityManagerFactoryOrderDiscount")publicLocalContainerEntityManagerFactoryBean entityManagerFactoryOrderDiscount(EntityManagerFactoryBuilder builder){returnbuilder
.dataSource(orderDiscountDataSource)
.properties(getVendorProperties(orderDiscountDataSource))
.packages(new String[]{"com.agen.orderdiscount"})
.persistenceUnit("orderDiscountPersistenceUnit")
.build();
}/*** 配置EntityManager实体
*@parambuilder
*@return实体管理器*/@Primary
@Bean(name= "entityManagerOrderDiscount")publicEntityManager entityManager(EntityManagerFactoryBuilder builder){returnentityManagerFactoryOrderDiscount(builder).getObject().createEntityManager();
}/*** 配置事务transactionManager
*@parambuilder
*@return事务管理器*/@Primary
@Bean(name= "transactionManagerOrderDiscount")publicPlatformTransactionManager transactionManagerOrderDiscount(EntityManagerFactoryBuilder builder){return newJpaTransactionManager(entityManagerFactoryOrderDiscount(builder).getObject());
}
}
View Code
其他数据源完整代码:
MyagenDataSourceConfig.java
packagecom.agen.config.datasource;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.boot.autoconfigure.orm.jpa.JpaProperties;importorg.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;importorg.springframework.context.annotation.Bean;importorg.springframework.context.annotation.Configuration;importorg.springframework.data.jpa.repository.config.EnableJpaRepositories;importorg.springframework.orm.jpa.JpaTransactionManager;importorg.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;importorg.springframework.orm.jpa.vendor.Database;importorg.springframework.transaction.PlatformTransactionManager;importorg.springframework.transaction.annotation.EnableTransactionManagement;importjavax.persistence.EntityManager;importjavax.sql.DataSource;importjava.util.HashMap;importjava.util.Map;/***@authorSXD
* @date 2017/12/04
* sql server数据库中数据源的 声明装载类
**/@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef= "entityManagerFactoryMyagen", //实体管理引用
transactionManagerRef = "transactionManagerMyagen", //事务管理引用
basePackages = {"com.agen.myagen"}) //设置 myagenDataSource应用到的包
public classMyagenDataSourceConfig {/*** 注入 我的基因网数据源*/@Autowired()
@Qualifier("myagenDataSource")privateDataSource myagenDataSource;/*** 注入JPA配置实体*/@AutowiredprivateJpaProperties jpaProperties;/*** 通过调用JPA配置实体中的解析方法,解析datasource中各属性的值
*@paramdataSource 数据源
*@return本数据源中各参数
* Map中设值分别为:
* hibernate-dialect 方言
* hibernate.hbm2ddl.auto DDL执行策略
* hibernate.physical_naming_strategy 命名策略
*
*这些和不同类型数据库密切相关的属性设置,不能设置在application.properties中,所以需要再不同的数据源中具体设置,赋值给JpaProperties*/
private MapgetVendorProperties(DataSource dataSource) {
jpaProperties.setDatabase(Database.SQL_SERVER);
Map 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);returnjpaProperties.getHibernateProperties(dataSource);
}/*** 配置EntityManagerFactory实体
*
*@parambuilder
*@return* packages 扫描@Entity注释的软件包名称
* persistenceUnit 持久性单元的名称。 如果只建立一个EntityManagerFactory,你可以省略这个,但是如果在同一个应用程序中有多个,你应该给它们不同的名字
* properties 标准JPA或供应商特定配置的通用属性。 这些属性覆盖构造函数中提供的任何值。*/@Bean(name= "entityManagerFactoryMyagen")publicLocalContainerEntityManagerFactoryBean entityManagerFactoryMyagen(EntityManagerFactoryBuilder builder) {returnbuilder
.dataSource(myagenDataSource)
.properties(getVendorProperties(myagenDataSource))
.packages(new String[]{"com.agen.myagen"})
.persistenceUnit("myagenPersistenceUnit")
.build();
}/*** 配置EntityManager实体
*
*@parambuilder
*@return实体管理器*/@Bean(name= "entityManagerMyagen")publicEntityManager entityManager(EntityManagerFactoryBuilder builder) {returnentityManagerFactoryMyagen(builder).getObject().createEntityManager();
}/*** 配置事务
*
*@parambuilder
*@return事务管理器*/@Bean(name= "transactionManagerMyagen")publicPlatformTransactionManager transactionManagerMyagen(EntityManagerFactoryBuilder builder) {return newJpaTransactionManager(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
packagecom.agen.myagen.entity;import javax.persistence.*;importjava.math.BigDecimal;importjava.sql.Timestamp;
@Entity
@Table(name= "xx_order", schema = "dbo", catalog = "geneshop")public classXxOrder {private intid;privateTimestamp createDate;privateTimestamp modifyDate;privateString address;privateBigDecimal amountPaid;privateString areaName;privateString consignee;privateBigDecimal couponDiscount;private intexchangePoint;privateTimestamp expire;privateBigDecimal fee;privateBigDecimal freight;privateString invoiceTitle;private booleanisAllocatedStock;private booleanisInvoice;privateTimestamp lockExpire;privateString memo;privateString name;privateBigDecimal offsetAmount;private intorderStatus;privateString paymentMethodName;private intpaymentStatus;privateString phone;privateBigDecimal promotionDiscount;privateString promotionName;private intrewardPoint;privateString shippingMethodName;private intshippingStatus;privateString sn;privateBigDecimal tax;private inttype;privateString zipCode;privateString memberorderno;privateInteger ordertype;privateBoolean distributeState;privateTimestamp ctime;privateString guid;privateString cbqrr;privateTimestamp cbqrTime;privateBoolean isCbqr;privateBoolean isSrqr;privateString srqrr;privateTimestamp srqrTime;privateString isShow;privateBoolean isHunantb;privateBoolean byCreditCard;privateXxMember xxMemberByMember;privateXxAdmin xxAdminByOperator;privateXxAdmin xxAdminByAdmin;
@Id
@Column(name= "id", nullable = false, precision = 0)public intgetId() {returnid;
}public void setId(intid) {this.id =id;
}
@Basic
@Column(name= "create_date", nullable = false)publicTimestamp getCreateDate() {returncreateDate;
}public voidsetCreateDate(Timestamp createDate) {this.createDate =createDate;
}
@Basic
@Column(name= "modify_date", nullable = false)publicTimestamp getModifyDate() {returnmodifyDate;
}public voidsetModifyDate(Timestamp modifyDate) {this.modifyDate =modifyDate;
}
@Basic
@Column(name= "address", nullable = false, length = 255)publicString getAddress() {returnaddress;
}public voidsetAddress(String address) {this.address =address;
}
@Basic
@Column(name= "amount_paid", nullable = false, precision = 6)publicBigDecimal getAmountPaid() {returnamountPaid;
}public voidsetAmountPaid(BigDecimal amountPaid) {this.amountPaid =amountPaid;
}
@Basic
@Column(name= "area_name", nullable = false, length = 255)publicString getAreaName() {returnareaName;
}public voidsetAreaName(String areaName) {this.areaName =areaName;
}
@Basic
@Column(name= "consignee", nullable = false, length = 255)publicString getConsignee() {returnconsignee;
}public voidsetConsignee(String consignee) {this.consignee =consignee;
}
@Basic
@Column(name= "coupon_discount", nullable = false, precision = 6)publicBigDecimal getCouponDiscount() {returncouponDiscount;
}public voidsetCouponDiscount(BigDecimal couponDiscount) {this.couponDiscount =couponDiscount;
}
@Basic
@Column(name= "exchange_point", nullable = false, precision = 0)public intgetExchangePoint() {returnexchangePoint;
}public void setExchangePoint(intexchangePoint) {this.exchangePoint =exchangePoint;
}
@Basic
@Column(name= "expire", nullable = true)publicTimestamp getExpire() {returnexpire;
}public voidsetExpire(Timestamp expire) {this.expire =expire;
}
@Basic
@Column(name= "fee", nullable = false, precision = 6)publicBigDecimal getFee() {returnfee;
}public voidsetFee(BigDecimal fee) {this.fee =fee;
}
@Basic
@Column(name= "freight", nullable = false, precision = 6)publicBigDecimal getFreight() {returnfreight;
}public voidsetFreight(BigDecimal freight) {this.freight =freight;
}
@Basic
@Column(name= "invoice_title", nullable = true, length = 255)publicString getInvoiceTitle() {returninvoiceTitle;
}public voidsetInvoiceTitle(String invoiceTitle) {this.invoiceTitle =invoiceTitle;
}
@Basic
@Column(name= "is_allocated_stock", nullable = false)public booleanisAllocatedStock() {returnisAllocatedStock;
}public void setAllocatedStock(booleanallocatedStock) {
isAllocatedStock=allocatedStock;
}
@Basic
@Column(name= "is_invoice", nullable = false)public booleanisInvoice() {returnisInvoice;
}public void setInvoice(booleaninvoice) {
isInvoice=invoice;
}
@Basic
@Column(name= "lock_expire", nullable = true)publicTimestamp getLockExpire() {returnlockExpire;
}public voidsetLockExpire(Timestamp lockExpire) {this.lockExpire =lockExpire;
}
@Basic
@Column(name= "memo", nullable = true, length = 255)publicString getMemo() {returnmemo;
}public voidsetMemo(String memo) {this.memo =memo;
}
@Basic
@Column(name= "name", nullable = false, length = 500)publicString getName() {returnname;
}public voidsetName(String name) {this.name =name;
}
@Basic
@Column(name= "offset_amount", nullable = false, precision = 6)publicBigDecimal getOffsetAmount() {returnoffsetAmount;
}public voidsetOffsetAmount(BigDecimal offsetAmount) {this.offsetAmount =offsetAmount;
}
@Basic
@Column(name= "order_status", nullable = false)public intgetOrderStatus() {returnorderStatus;
}public void setOrderStatus(intorderStatus) {this.orderStatus =orderStatus;
}
@Basic
@Column(name= "payment_method_name", nullable = true, length = 255)publicString getPaymentMethodName() {returnpaymentMethodName;
}public voidsetPaymentMethodName(String paymentMethodName) {this.paymentMethodName =paymentMethodName;
}
@Basic
@Column(name= "payment_status", nullable = false)public intgetPaymentStatus() {returnpaymentStatus;
}public void setPaymentStatus(intpaymentStatus) {this.paymentStatus =paymentStatus;
}
@Basic
@Column(name= "phone", nullable = false, length = 255)publicString getPhone() {returnphone;
}public voidsetPhone(String phone) {this.phone =phone;
}
@Basic
@Column(name= "promotion_discount", nullable = false, precision = 6)publicBigDecimal getPromotionDiscount() {returnpromotionDiscount;
}public voidsetPromotionDiscount(BigDecimal promotionDiscount) {this.promotionDiscount =promotionDiscount;
}
@Basic
@Column(name= "promotion_name", nullable = true, length = 255)publicString getPromotionName() {returnpromotionName;
}public voidsetPromotionName(String promotionName) {this.promotionName =promotionName;
}
@Basic
@Column(name= "reward_point", nullable = false, precision = 0)public intgetRewardPoint() {returnrewardPoint;
}public void setRewardPoint(intrewardPoint) {this.rewardPoint =rewardPoint;
}
@Basic
@Column(name= "shipping_method_name", nullable = true, length = 255)publicString getShippingMethodName() {returnshippingMethodName;
}public voidsetShippingMethodName(String shippingMethodName) {this.shippingMethodName =shippingMethodName;
}
@Basic
@Column(name= "shipping_status", nullable = false)public intgetShippingStatus() {returnshippingStatus;
}public void setShippingStatus(intshippingStatus) {this.shippingStatus =shippingStatus;
}
@Basic
@Column(name= "sn", nullable = false, length = 100)publicString getSn() {returnsn;
}public voidsetSn(String sn) {this.sn =sn;
}
@Basic
@Column(name= "tax", nullable = false, precision = 6)publicBigDecimal getTax() {returntax;
}public voidsetTax(BigDecimal tax) {this.tax =tax;
}
@Basic
@Column(name= "type", nullable = false)public intgetType() {returntype;
}public void setType(inttype) {this.type =type;
}
@Basic
@Column(name= "zip_code", nullable = false, length = 255)publicString getZipCode() {returnzipCode;
}public voidsetZipCode(String zipCode) {this.zipCode =zipCode;
}
@Basic
@Column(name= "memberorderno", nullable = true, length = 255)publicString getMemberorderno() {returnmemberorderno;
}public voidsetMemberorderno(String memberorderno) {this.memberorderno =memberorderno;
}
@Basic
@Column(name= "ordertype", nullable = true)publicInteger getOrdertype() {returnordertype;
}public voidsetOrdertype(Integer ordertype) {this.ordertype =ordertype;
}
@Basic
@Column(name= "distributeState", nullable = true)publicBoolean getDistributeState() {returndistributeState;
}public voidsetDistributeState(Boolean distributeState) {this.distributeState =distributeState;
}
@Basic
@Column(name= "ctime", nullable = true)publicTimestamp getCtime() {returnctime;
}public voidsetCtime(Timestamp ctime) {this.ctime =ctime;
}
@Basic
@Column(name= "guid", nullable = true, length = 255)publicString getGuid() {returnguid;
}public voidsetGuid(String guid) {this.guid =guid;
}
@Basic
@Column(name= "cbqrr", nullable = true, length = 255)publicString getCbqrr() {returncbqrr;
}public voidsetCbqrr(String cbqrr) {this.cbqrr =cbqrr;
}
@Basic
@Column(name= "cbqr_time", nullable = true)publicTimestamp getCbqrTime() {returncbqrTime;
}public voidsetCbqrTime(Timestamp cbqrTime) {this.cbqrTime =cbqrTime;
}
@Basic
@Column(name= "is_cbqr", nullable = true)publicBoolean getCbqr() {returnisCbqr;
}public voidsetCbqr(Boolean cbqr) {
isCbqr=cbqr;
}
@Basic
@Column(name= "is_srqr", nullable = true)publicBoolean getSrqr() {returnisSrqr;
}public voidsetSrqr(Boolean srqr) {
isSrqr=srqr;
}
@Basic
@Column(name= "srqrr", nullable = true, length = 255)publicString getSrqrr() {returnsrqrr;
}public voidsetSrqrr(String srqrr) {this.srqrr =srqrr;
}
@Basic
@Column(name= "srqr_time", nullable = true)publicTimestamp getSrqrTime() {returnsrqrTime;
}public voidsetSrqrTime(Timestamp srqrTime) {this.srqrTime =srqrTime;
}
@Basic
@Column(name= "is_show", nullable = true, length = 255)publicString getIsShow() {returnisShow;
}public voidsetIsShow(String isShow) {this.isShow =isShow;
}
@Basic
@Column(name= "is_hunantb", nullable = true)publicBoolean getHunantb() {returnisHunantb;
}public voidsetHunantb(Boolean hunantb) {
isHunantb=hunantb;
}
@Basic
@Column(name= "by_credit_card", nullable = true)publicBoolean getByCreditCard() {returnbyCreditCard;
}public voidsetByCreditCard(Boolean byCreditCard) {this.byCreditCard =byCreditCard;
}
@Overridepublic booleanequals(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;
}
@Overridepublic inthashCode() {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);returnresult;
}
@ManyToOne
@JoinColumn(name= "member", referencedColumnName = "id", nullable = false)publicXxMember getXxMemberByMember() {returnxxMemberByMember;
}public voidsetXxMemberByMember(XxMember xxMemberByMember) {this.xxMemberByMember =xxMemberByMember;
}
@ManyToOne
@JoinColumn(name= "operator", referencedColumnName = "id")publicXxAdmin getXxAdminByOperator() {returnxxAdminByOperator;
}public voidsetXxAdminByOperator(XxAdmin xxAdminByOperator) {this.xxAdminByOperator =xxAdminByOperator;
}
@ManyToOne
@JoinColumn(name= "admin", referencedColumnName = "id")publicXxAdmin getXxAdminByAdmin() {returnxxAdminByAdmin;
}public voidsetXxAdminByAdmin(XxAdmin xxAdminByAdmin) {this.xxAdminByAdmin =xxAdminByAdmin;
}
}
View Code
OrderRepository.java
packagecom.agen.myagen.repository;importcom.agen.myagen.entity.XxAdmin;importcom.agen.myagen.entity.XxOrder;importorg.springframework.data.jpa.repository.JpaRepository;importjava.util.List;public interface OrderRepository extends JpaRepository{
ListfindTop10ByXxAdminByOperator(XxAdmin xxAdminByOperator);
@Override
XxOrder findOne(Integer integer);
}
View Code
Member.java
packagecom.agen.orderdiscount.entity;import lombok.*;importlombok.experimental.Accessors;importorg.hibernate.annotations.GenericGenerator;import javax.persistence.*;
@Data(staticConstructor= "of")
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain= true)
@Entity
@GenericGenerator(name= "uuid2", strategy = "org.hibernate.id.UUIDGenerator")public classMember {
@Id
@GeneratedValue(generator= "uuid2")privateString memberId;
@Column(nullable= false)
@NonNullprivateInteger memberGrade;
@Column(nullable= false)
@NonNullprivateString orderSn;
}
View Code
MemberRepositpry.java
packagecom.agen.orderdiscount.repository;importcom.agen.orderdiscount.entity.Member;importorg.springframework.data.jpa.repository.JpaRepository;importjava.util.List;public interface MemberRepository extends JpaRepository{
@Override
Member save(Member member);
ListfindByMemberGrade(Integer memberGrade);
}
View Code
1.我这里myagen数据源下数据库中表早已存在,是根据hibernate反转工具生成的几个需要的类
【hibernate反转工具怎么使用】
2.和数据库打交道的持久化框架是spring boot自带的spring-data-jpa。
【spring-data-jpa怎么使用】
3.Member实体中使用了lombok,一个java的一个奇技淫巧
4.关于Member.java实体,因为这个对应的是orderdiscount数据源,也就是主数据源,是mysql这边的,是先写了实体之后,自动根据第三步中设置在map中的
hibernate.physical_naming_strategy
,所以生成的数据表中的字段,应该是不带下划线的。
=========================================================================================================================================
5》最后再controller层,依次调用各种数据源对应的各个包下的各种repository操作进行操作
这一层,什么也不用多说了
MainController.java
packagecom.agen.controller;importcom.agen.myagen.entity.XxAdmin;importcom.agen.myagen.entity.XxOrder;importcom.agen.myagen.repository.OrderRepository;importcom.agen.orderdiscount.entity.Member;importcom.agen.orderdiscount.repository.MemberRepository;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Controller;importorg.springframework.web.bind.annotation.RequestMapping;importjava.util.List;importjava.util.Objects;importjava.util.UUID;
@Controllerpublic classMainController {
@AutowiredprivateOrderRepository orderRepository;
@AutowiredprivateMemberRepository memberRepository;
@RequestMapping("lo")public voidgetOrder(){
XxOrder xxOrder= orderRepository.findOne(1510);
System.out.println("sql server数据库查到order编号:"+xxOrder.getSn());
Member member= newMember();
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 list = memberRepository.findByMemberGrade(2);if(Objects.nonNull(list) && list.size() > 0){
list.forEach(i->{
System.out.println("mysql数据库查出order编号:"+i.getOrderSn());
});
}
}
}
}
View Code
然后启动,启动可以看到下面这些信息:
最后,访问一下这个地址:
可以看到和多数据源交互的 SQL语句打印出来:
======================================================================================================
好了 ,终于完成了!!!!