Tuesday, November 22, 2011

Setting up Hibernate with an eclipse JPA project



In this tutorial I will be creating a sample JPA application from scratch in which we will create a single entity representing a user.

We will need to have the following available:

  1. Eclipse IDE for Java EE developers, which can be downloaded from eclipse download page , I am using Indigo.
  2. hibernate-distribution-3.6.7.Final-dist which can be downloaded from hibernate download page.
  3. Oracle or Oracle XE installation. Oracle XE can be downloaded from oracle xe download page.
  4. SLF4J can be downloaded from slf4j download page.
  5. Create a folder in d:\workspaces and name it hibernate_lib, place the following files inside of it:
  • The two jars hibernate3.jar,hibernate-jpa-2.0-api-1.0.1.Final.jar which can be found in the hibernate distribution.
  • antlr-2.7.6.jar, commons-collections-3.1.jar,dom4j-1.6.1.jar,javaassist-3.12.0.GA.jar, jta-1.1.jar, and slf4j-api-1.6.1.jar. Those files can be found inside the HIBERNATE_DISTRIBUTION/lib/required
  • ojdbc4.jar which can be found in ORACLE_XE_HOME\app\oracle\product\10.2.0\server\jdbc\lib
  • slf4j-simple-1.6.2.jar from the SLF4J distribution.







Now we'll start by creating a new database schema and user table :




After preparing our database, we will start creating our JPA project by following these steps:

  • Create a new JPA project, in the New JPA project wizard enter JPAProject as your project name
  • Click next until you reach the JPA facet screen, select the JPA implementation as a user library, click on manage libraries and create a new library, name it "Hibernate" and add the two jar files we placed in the d:\workspaces\hibernate_lib to it

  • Click on the add connection link, the New connection profile screen will popup, select your database type as Oracle and name the connection "DB_AUTH", then click next

  • In the New driver screen, select Oracle Thin Driver for version 10
  • Click on the JAR list tab and remove the default jar found in the list, then add ojdbc4.jar which we placed in d:\workspaces\hibernate_lib folder

  • Click OK, then you will need to specify your connection details, test your connection then click Finish

  • Select DB_AUTH as your connection from the drop down list, then click finish

  • Right click the project, select New the JPA entities from tables wizard, select DB_AUTH connection in case its not selected and then select the bh_user from the tables list

  • Click next, then select the "sequence" from the key generator drop down list,  enter "$table_seq" as your sequence name, and com.thebinaryheap.model.entity as your package name
  • Eclipse will generate a file called BhUser.java representing your user entity





  • Make sure your persistence.xml file looks similar to the following


  • Finally to test our code we'll use the following class

No comments:

Post a Comment