Saturday, September 15, 2012

How to use JPA using data-source on tomcat?

How to use JPA using data-source on tomcat?

Step :1 Add following details to context.xml of tomcat server
    <Resource auth="Container"
   driverClassName="com.mysql.jdbc.Driver"
   maxActive="20"
   maxIdle="10"
   maxWait="-1"
   name="jdbc/myconnection"
   password="admin"
   type="javax.sql.DataSource"
   url="jdbc:mysql://localhost:3306/test?auto_reconnect=true&amp;relaxAutoCommit=true"
   username="root"/>

Step 2 : Add resource-ref in web.xml
<resource-ref>
      <description>DB Connection</description>
      <res-ref-name>jdbc/myconnection</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>


Step 3: Add following details in persistence.xml
<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"
    version="1.0">
<persistence-unit name="jpa" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <non-jta-data-source>java:comp/env/jdbc/myconnection</non-jta-data-source>
     <properties>
            <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/myconnection"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
            <property name="hibernate.id.new_generator_mappings" value ="true"/>
  
        </properties>
    </persistence-unit>
</persistence>


Now your data-source is ready to connect database.

15 comments:

Thanks for your valuable comment. You comment will go live soon.