Tuesday, September 27, 2011

Spring and Hibernate Integration (MySQL)

Include the Hibernate libs then use this to create the beans needed:

<bean id="myDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/db" />
<property name="username" value="root" />
<property name="password" value="admin" />
</bean>

<bean id="mySessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="annotatedClasses">
<list>
<value>com.something.entity</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>

Deploying EJB3 into openEJB

ref: http://openejb.apache.org/3.0/deployments.html

<openejb><Deployments jar="c:\my\app\superEjbs.jar">
or relatively to openejb.base:
<openejb><Deployments jar="app\superEjbs.jar">

For in depth info link:
http://blog.lckymn.com/2009/10/17/java-ee-application-development-
using-tomcat-openejb-and-hibernate/

openEJB3 and MySQL DS Config

Configuration in openejb.xml (bundled in tomcat conf):

<Resource id="MySQL Database" type="DataSource">
#MySQL example
#
#This connector will not work until you download the driver at:
#http://www.mysql.com/downloads/api-jdbc-stable.html

JdbcDriver com.mysql.jdbc.Driver
JdbcUrl jdbc:mysql://localhost/iim
UserName
Password
</Resource>

The drive for MySQL is required by openEJB (should go into the tomcat lib, not the openEJB3 lib)

Before hibernate can be used, it need to be installed again into the tomcat lib.

persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
version="1.0">
<persistence-unit name="iimdb">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>iimdb</jta-data-source>
<non-jta-data-source>iimdbNonJta</non-jta-data-source>
<properties>
<!-- this is to control the auto drop and create of schema -->
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.show.sql" value="true"></property>
</properties>
</persistence-unit>
</persistence>