Using JPA with Hibernate to Generate Entities from Database Tables

Programming · notes

Voir tous les documents en programmation

Using JPA with Hibernate to generate Entities from database tables

Making sure Eclipse runs over a JDK (not a JRE)

It is critical to run Eclipse with a JDK, not a JRE, for JPA and Hibernate tools to work. Unexpected

errors may occur otherwise, especially with code generation from database tables.

On Linux, Eclipse most likely already runs over a JDK (openjdk).

On Windows, Eclipse most likely does not run over a JDK. It runs on a JRE. To make it run over a JDK :

  • Open the Control Panel and check that a JDK is installed. If no JDK is installed, you need to

-

-

install one.

Launch Eclipse. Go to Window > Preferences > Java > Installed JREs.

You need to make sure that the active entry points to a JDK directory. You may need to click

the Add… button and manually add the JDK.

Make sure Hibernate Tools is installed

To see if Hibernate Tools is installed, in Eclipse go to File > New, select Other…, and, in the Wizards

box, type « Hib ». If the list ends up empty, this means Hibernate Tools is not installed :

[email protected] © 2019

CC BY-NC-ND

To install it :

Help > Install New Software…

Next to the Work With button, click the Add button.

Name : JBossTools

URL : http://download.jboss.org/jbosstools/photon/stable/updates/

(as stated in the following page : https://tools.jboss.org/downloads/jbosstools/2018-

09/4.9.0.Final.html#update_site)

Click Add.

Install Hibernate Tools :

[email protected] © 2019

CC BY-NC-ND

Click Next >

You will be the installation progress in the bottom-right corner of the main Eclipse window.

Create JPA project

This tutorial assumes that you already have a database connection set up in the Data Source Explorer

called NorthwindH2.

Publicité

Refer to the document Using_DataSourceExplorer for information about how to set up a connection.

To start with, go the File menu, select New :

[email protected] © 2019

CC BY-NC-ND

Fill in the dialog with default information for the runtime and Configuration fields :

[email protected] © 2019

CC BY-NC-ND

In the Target runtime field, make sure you select a line with a JDK entry ! (not JRE) :

[email protected] © 2019

CC BY-NC-ND

Click Next > twice, you reach this dialog :

Make sure JPA Implementation type is set : Disable Library Configuration, as we will use Maven to

reference Hibernate.

« Hibernate (JPA 2.1) » should be selected in the Platform section.

Click Finish.

Converting the JPA Project to Maven

Right-click the project node in Project Explorer, and select Configure > Convert to Maven Project.

Leave default values in the dialog and click Finish.

The pom.xml file will automatically be opened.

Add the following block after the closing </build> tag :

<dependencies>

[email protected] © 2019

CC BY-NC-ND

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-entitymanager</artifactId>

<version>5.4.2.Final</version>

</dependency>

<dependency>

<groupId>org.hibernate</groupId>

<artifactId>hibernate-jpamodelgen</artifactId>

<version>5.4.2.Final</version>

</dependency>

</dependencies>

Publicité

Creating the Hibernate config file

File menu > New > Hibernate Configuation file (.cfg.xml) (in the Hibernate section)

Click Next >

[email protected] © 2019

CC BY-NC-ND

Click Next > again.

[email protected] © 2019

CC BY-NC-ND

In the definition window, fill in the details as illustrated above.

Note :

 Hibernate version should be 5.2

 The connection URL contains the path of the database file on your computer (the above

image is an example only)

 Make sure the Create a console configuration checkbox is checked

Then click Next >

[email protected] © 2019

CC BY-NC-ND

In the Options tab make sure the H2 dialect is selected :

[email protected] © 2019

CC BY-NC-ND

Click Finish. The file hibernate.cfg.xml is created under the ‘src’ folder. Switch to the Source tab (at

the bottom) and add the following lines (in bold characters) :

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property

name="hibernate.connection.driver_class">org.h2.Driver</property>

<property name="hibernate.connection.url">jdbc:h2:...</property>

<property name="hibernate.connection.username">sa</property>

<property name="hibernate.default_catalog">N2NORTHWINDDATABASE</property>

<property name="hibernate.default_schema">PUBLIC</property>

Publicité

<property

name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>

<property name="hibernate.globally_quoted_identifiers">true</property>

<property name="hibernate.show_sql">true</property>

</session-factory>

</hibernate-configuration>

[email protected] © 2019

CC BY-NC-ND

Editing persistence.xml

Edit persistence.xml so that it looks like this :

<?xml version="1.0" encoding="UTF-8"?>

<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence

http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">

<persistence-unit name="fc.JPAMaven" transaction-type="RESOURCE_LOCAL">

<properties>

<property name="hibernate.ejb.cfgfile"

value="./hibernate.cfg.xml" />

</properties>

</persistence-unit>

</persistence>

Generating Java files

Now in Project Explorer, right-click the project node, select JPA tools and Generate Entities from

Tables… (not Generate Tables from Entities !)

The following dialog appears :

Fill in the details as above.

You will see this in the bottom right corner of the Eclipse window :

Java files have been generated :

[email protected] © 2019

CC BY-NC-ND

Each file looks like this :

[email protected] © 2019

CC BY-NC-ND

Publicité

Writing a small application

You may now test your JPA connection with sample code. Make sure the string passed to

createEntityManagerFactory matches the name of your persistence unit in persistence.xml.

package fc.JPAMaven;

import java.util.List;

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

import javax.persistence.TypedQuery;

import thedbmodel.Suppliers;

public class Application

{

public static void main(String[] args)

{

EntityManagerFactory emf = Persistence.

createEntityManagerFactory("fc.JPAMaven");

EntityManager em = emf.createEntityManager();

String str = "SELECT s FROM Suppliers s";

TypedQuery<Suppliers> query = em.createQuery(str, Suppliers.class);

List<Suppliers> suppliers = query.getResultList();

for (Suppliers s : suppliers)

{

System.out.println("nom = "+ s.getLastName());

}

em.close();

emf.close();

}

}

[email protected] © 2019

CC BY-NC-ND