In the How do I store object in Hibernate? example you’ll see how tho store objects into database. In this example we’ll extend the LabelService
class and add the capability to get or query object from database.
package org.kodejava.hibernate.service;
import org.hibernate.Session;
import org.kodejava.hibernate.SessionFactoryHelper;
import org.kodejava.hibernate.model.Label;
public class LabelService {
public Label getLabel(Long id) {
Session session =
SessionFactoryHelper.getSessionFactory().getCurrentSession();
session.beginTransaction();
// We get back Label object from database by calling the Session
// object get() method and passing the object type and the object
// id to be read.
Label label = session.get(Label.class, id);
session.getTransaction().commit();
return label;
}
}
package org.kodejava.hibernate;
import org.kodejava.hibernate.model.Label;
import org.kodejava.hibernate.service.LabelService;
public class LoadDemo {
public static void main(String[] args) {
// Create an instance of LabelService.
LabelService service = new LabelService();
// We call the getLabel() method and pass the label id to load it
// from the database and print out the label string.
Label label = service.getLabel(1L);
System.out.println("label = " + label);
}
}
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.6.9.Final</version>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.0.33</version>
</dependency>
</dependencies>