2天時間,終於把spring boot下配置鏈接多種不一樣類型數據庫,配置多數據源實現!html
======================================================================================================java
spring boot對多種不一樣類型數據庫,多數據源配置使用mysql
多數據源配置相關官方API:https://docs.spring.io/spring-boot/docs/current/api/web
環境以下:spring
開發環境IDE:IntelliJ IDEAsql
spring boot版本:1.5.9數據庫
hibernate版本:5.0.12api
多數據源: sql server2008 和 mysql 5.5app
======================================================================================================框架
實現多數據源的配置鏈接,主要思路以下:
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(); } }
===============================================================================================================================================
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()); } }
其餘數據源完整代碼:
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()); } }
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; } }
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); }
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; }
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); }
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()); }); } } } }
而後啓動,啓動能夠看到下面這些信息:
最後,訪問一下這個地址:
能夠看到和多數據源交互的 SQL語句打印出來:
======================================================================================================
好了 ,終於完成了!!!!