1. 程式人生 > 實用技巧 >讓Liferay的Service Builder連線其他資料庫

讓Liferay的Service Builder連線其他資料庫

參考:http://www.huqiwen.com/2016/08/11/service-builder-use-other-database/

2016年08月11日Liferay評論 2 條閱讀 4,919 views 次

在Liferay裡面使用ServiceBuilder預設情況下連線的資料庫是Liferay本身的資料庫,在某些場景和需求下,我們可能需要連線另外的資料庫或者資料來源。ServiceBuilder預設情況下已經提供了相關的支援,需要做下簡單的配置。

第一步,在service.xml裡面為對應的實體指定對應的資料來源等。在entity裡面定義data-source、session-factory、tx-manager

在對應的entity裡面新增如下配置,

data-source="sampleDataSource"

session-factory=“sampleSessionFactory”

tx-manager="sampleTransactionManager"

上面的名稱可以自己定義,放在entity的屬性裡面。

第二步:在自己專案的META-INF裡面建立ext-spring.xml檔案

裡面的內容如下,將下面的內容全部複製到ex-spring.xml裡面,注意裡面的id名稱和第一步裡面的保持一致。

<?xml version="1.0"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
 <bean id="sampleDataSourceTarget" class="com.liferay.portal.dao.jdbc.util.DataSourceFactoryBean">
 <property name="propertyPrefix" value="jdbc.custom.default." />
 </bean>
 <bean id="sampleDataSource" class="org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy">
 <property name="targetDataSource">
 <ref bean="sampleDataSourceTarget" />
 </property>
 </bean>
 <bean id="sampleHibernateSessionFactory" class="com.liferay.portal.spring.hibernate.PortletHibernateConfiguration">
 <property name="dataSource">
 <ref bean="sampleDataSource" />
 </property>
 </bean>
 <bean id="sampleSessionFactory" class="com.liferay.portal.dao.orm.hibernate.SessionFactoryImpl">
 <property name="sessionFactoryImplementor">
 <ref bean="sampleHibernateSessionFactory" />
 </property>
 </bean>
 <bean id="sampleTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
 <property name="dataSource">
 <ref bean="sampleDataSource" />
 </property>
 <property name="sessionFactory">
 <ref bean="sampleHibernateSessionFactory" />
 </property>
 </bean>
</beans>

第三步:配置相關資料來源

可在第二步裡面看到,我們指定的其他第三方的資料來源是採用的如下程式碼:

 <property name="propertyPrefix" value="jdbc.custom.default." />

我們可以在portal-setup-wizard.properties或者是portal-ext.properties,裡面配置其他資料庫的連線資訊。配置方法如下:

jdbc.custom.default.driverClassName=xxx

jdbc.custom.default.url=xxxx

jdbc.custom.default.username=xxx

jdbc.custom.default.password=xxx

也就是字首保持和我們有在ext-spring.xml裡面配置的一致即可。

說明:

ext-spring.xml裡面的資料來源還可以採用如下的配置方法:

<bean id="sampleDataSourceTarget" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 <property name="driverClassName" value="${jdbc.sample.driverClassName}" />
 <property name="url" value="${jdbc.sample.url}" />
 <property name="username" value="${jdbc.sample.username}" />
 <property name="password" value="${jdbc.sample.password}" />
</bean>

也就是在這裡指定各項的配置引數,我更推薦前面的方法。

第四步:和普通的serviceBuilder一樣使用。

其他地方的使用就和在liferay同一個資料庫裡面的表是一樣的用法了。但是這裡需要注意的是,當我們連線其他第三方資料庫時,serviceBuilder不會在第三方資料庫裡面執行自動建表的操作,需要我們手動的建立相關表

其他的查詢等用法就沒有區別了