Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to use Hibernate with Annotations on the NetBeans Platform

DZone's Guide to

How to use Hibernate with Annotations on the NetBeans Platform

· Database Zone
Free Resource

Learn how to create flexible schemas in a relational database using SQL for JSON.

In this tutorial I want to show you how to use Hibernate with annotations in an application on the NetBeans Platform.

Below I use the same sample used in the DZone tutorial by Constantin Drabo. The tutorial you are now reading aims to be an alternative to the use of Hibernate with XML files. I don't want to rate one of the possibilities as "the better one". That depends completely on your personal taste.

We start with the little patient administration example that Geertjan showed us how to create at the NetBeans Platform Certified training in Braunschweig:

As you can see, we have four modules:

  • PatientBranding to brand the menu
  • PatientModel with the Information of the patient
  • PatientEditor to create and edit the patient
  • PatientViewer to show the patient nodes

As the first step, we add a new library wrapper module, named Hibernate. In the main menubar, we click on File --> New Project --> NetBeans Modules and then we choose "Library Wrapper Module".

Then we choose the libraries we need:

 

Note: The versions above could be different and newer but for this tutorial the above are OK.

Click Next and give this module the project name "Hibernate" and the code name base "org.jboss.hibernate".

When you click Finish, you should see that the module is added to the "PatientApplication".

After that, we need to create a new module, named "DatabaseConnection". The code name base could be something like "de.patient.databaseconnection" or whatever else you want to use to uniquely identify it.

In this module, we need to add the "META-INF" folder with the "persistence.xml" file:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" 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">
<persistence-unit name="Patientlist" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>de.patient.model.Patient</class>
    <properties>
<property name="hibernate.connection.username" value="username"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value="password"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost/patientdb"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>

This file configures the database connection and the classes we want to persist.

After that, we add a package named “log4j”, to contain the "log4j.properties" file.

We right click on the package and choose New --> Others --> Other --> Property File, using the name "log4j".

In this file we add the following configuration:

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=warn, stdout

Now we have the configuration ready and can add a dependency in the DatabaseConnection module, so that it can make use of the Hibernate module.

We right click the module in the Projects window, choose Properties and then go to the Libraries tab. There, add a dependency so that we can filter the Hibernate module that we already added to our application. We click OK and you should see this:

Now we add a Java file to the package “de.patient.databaseconnection”. Name it "DatabaseEntityManager.java", with this content:

package de.patient.databaseconnection;

import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

public class DatabaseEntityManager {

static {
getEntityManager();
}

public DatabaseEntityManager() {
}
private static EntityManagerFactory entityManagerFactory;
private static EntityManager entityManager;

public static EntityManager getEntityManager() {

if (entityManager == null) {
try {
entityManagerFactory = javax.persistence.Persistence.
createEntityManagerFactory("Patientlist");
} catch (java.lang.IllegalStateException ex) {
try {
Thread.sleep(2000);
} catch (InterruptedException ex1) {
Logger.getLogger(DatabaseEntityManager.class.getName()).
log(Level.SEVERE, null, ex1);
}
getEntityManager();
}
entityManager = entityManagerFactory.createEntityManager();
}
return entityManager;
}

public static EntityManagerFactory getEntityManagerFactory() {
if (entityManagerFactory == null) {
entityManagerFactory = javax.persistence.Persistence.createEntityManagerFactory("Patientlist");
entityManager = entityManagerFactory.createEntityManager();
}
return entityManagerFactory;
}
}

After that, we need to make this package public so that other classes can access it. We right-click on the module in the Projects window, choose Properties, and then choose API Versioning and then click the "Public Packages" checkbox, as shown below: 

 

 Now our project should look like this:

 

Now we add the entity class we want to persist. To do that, we only need to add a dependency to the Hibernate module on the PatientModel module... and then add some lines to the existing "Patient.java" class.

In the "Patient.java" class, change this line:

public class Patient {  

 ...to this line:

@Entity
public class Patient implements Serializable {

And also make sure to add the import statement for "java.io. Serializable".

Next, add an ID attribute:

@Id
@GeneratedValue
private Integer patientId;

Finally, we need to add the default constructor to the class:

public Patient() {

}

That’s all we need to tweak in the Patient class.

Next, let's add a "Refresh" function to the "PatientViewer", otherwise we won´t see that our newly added functionaility actually works.

Open the "PatientViewer" module and then open the "PatientEditorTopComponent" class.

Next, look for these three statements in the constructor:

        Children kids = Children.create(new PatientChildFactory(), true
em.setRootContext(new RootNode(kids));
associateLookup(ExplorerUtils.createLookup(em, getActionMap()));

 Instead of the above, we create a new function:

        public void refreshNode() {
    Children kids = Children.create(new PatientChildFactory(), true);
    em.setRootContext(new RootNode(kids));
     }

And then delete the first two statements of the three statements you found in the constructor, ending up with the following instead:

refreshNode();
associateLookup(ExplorerUtils.createLookup(em, getActionMap()));

After that we have a new method for refreshing the node. 

Now open the "PatientEditor" module. Add the Hibernate and DatabaseConnection modules as dependencies, so that we can get access to their classes.

After that, we add some buttons to the form, such as these:

Then we can start to add some functions to the buttons above, like this for the "Add" button:

        if (DatabaseEntityManager.getEntityManager().getTransaction().isActive()) {
DatabaseEntityManager.getEntityManager().getTransaction().rollback();
DatabaseEntityManager.getEntityManager().getTransaction().begin();
} else {
DatabaseEntityManager.getEntityManager().getTransaction().begin();
}

Patient patient = new Patient(namefield.getText(), illnessfield.getText());
DatabaseEntityManager.getEntityManager().persist(patient);
DatabaseEntityManager.getEntityManager().getTransaction().commit();
JOptionPane.showMessageDialog(this, "saving successful", "Congratulation", JOptionPane.INFORMATION_MESSAGE);
PatientViewerTopComponent.findInstance().refreshNode();

Next, try to run the application, after a "Clean and Build" on the project. Add some new patients with their illnesses. We will not see them in the list on the left side, because we must add the database to the "ChildFactory" first. But if you save the data and have a look in your database you should see a new table Patient with an ID, Name, and Illness.

Sure, we want to have them added to our list on the left side so we have to add the database to the "ChildFactory". Let's do so now.  Change the function "createKeys(List<Patient> list)", by adding the database query there:

        Query qa = DatabaseEntityManager.getEntityManager().createQuery("from Patient as p");
Iterator ite_a = qa.getResultList().iterator();
while (ite_a.hasNext()) {
Patient tmpPatient = new Patient("", "");
tmpPatient = (Patient) ite_a.next();
list.add(tmpPatient);
}
return true;

That’s all we need to do! We have completed the application and can try to see if everything works. You can also add some code to the "Cancel" and "Refresh" buttons, if you like.

Hope this helps you get started with the NetBeans Platform in combination with Hibernate annotation. And after you have gone through the above, you should compare the result to Constantin Drabo's tutorial to see which approach you prefer!

 

Create flexible schemas using dynamic columns for semi-structured data. Learn how.

Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}