Monday, December 5, 2016

Connecting to Different Database in Liferay


We  already know how to create service builder in Liferay. When we use service builder all our tables goes to default database that is mention in portal-ext.properties or portal-setup-wizard.properties.

But sometimes we need to create tables in a separate database so that all liferay related tables are in default database and our custom tables in another database.So today we will see how to connect Liferay with 2 databases.

So lets start this step by step:-


Step 1:-Create Project with Service.xml
You can create a project and create service.xml inside this.For detail you may refer Service Builder in Liferay. Now open service.xml and paste this content and build service:-

service.xml

Explanation:-
We already know Service Builder in Detail. Here we use one extra attribute data-source which help us to connect with different database.


Step 2:-Create table in database
Normally when we use service builder table is created automatically but when we connect to different database we need to create table manually.You can use this command for table creation:-



Step 3:-Create datasource
Open your META-INF folder and create a file ext-spring.xml as:-

ext-spring.xml

Explanation:-
1)Here you can see bean id is secondDataSource which is exactly same as data-source attribute of service.xml. My default database is aditya and second database is aditya2.

2)You can change your database name, url, password etc according to your database.

3)If you want to perform only get operation you can delete:-

<bean id="liferayTransactionManager"   class="">
         <property name="" ref="" />
         <property name="" value="" />
         <property name="" ref="" />
</bean>

Note:- When you remove liferayTransactionManager bean you cannot perform add,delete and update operation.



Step 4:-Use the Services
Now simply create you portlet and use the services. Open your controller and paste this:-

DbTest.java





Now you can deploy your portlet and check the output.

Project Structure:-



You can Download Source code from  Connect to different database. 


No comments:

Post a Comment

Total Pageviews

Number Of Unique Visitor

Free counters!