How to get started with hibernate in java. Create a simple class and database schema for demostration.
Tech-Today

How to get started with hibernate in java. Create a simple class and database schema for demostration.


Since, I've always been using different database sometimes I get confused how to implement the others. Like hibernate, where the configuration must be properly set.

*This help assumes that you have already created a java project in eclipse that has

Things that need to be setup:

1.) In your java project include the required jar files, download the hibernate core: http://sourceforge.net/projects/hibernate/files/hibernate3/3.3.2.GA/hibernate-distribution-3.3.2.GA-dist.zip/download. Extract in a directory, copy all the jar in the folder hibernate-distribution-3.3.2.GA/lib/required and include in your java project.

2.) You also need to download the slf4j-1.5.8, and include in your project the slf4j-simple-1.5.8.jar

3.) In the src folder of your java project add the hibernate.cfg.xml configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/anime</property>
<property name="hibernate.connection.username">ipiel</property>
<property name="hibernate.connection.password">q2dm1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show_sql">false</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="current_session_context_class">thread</property>
<mapping resource="Anime.hbm.xml" />
</session-factory>
</hibernate-configuration>

*mysql database is used

4.) Since, I'm always using Anime as example, let's create an Anime.hbm.xml file (in the src directory also):

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="demo.hibernate">
<class name="Anime">
<id name="id" column="id" type="integer" length="10">
<generator class="increment" />
</id>
<property name="name" column="name" type="string" length="50"></property>
</class>
</hibernate-mapping>

*The mysql database schema; table=Anime, has 2 fields: id and name

5.) Create the following files in the src directory:

public class Anime {
private int id;
private String name;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return name;
}
}


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class SessionFactoryUtil {
private static SessionFactory sessionFactory;

static {
sessionFactory = new Configuration().configure().buildSessionFactory();
}

public static SessionFactory getInstance() {
return sessionFactory;
}

public void openSession() {
sessionFactory.openSession();
}

public Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}

public static void close() {
if(sessionFactory != null) {
sessionFactory.close();
}
sessionFactory = null;
}
}


import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Runner {
private static final Logger logger = LoggerFactory.getLogger(Runner.class);

public static void main(String args[]) {
new Runner();
}

public Runner() {
Anime x = new Anime();
x.setName("Gundam Unicorn");
Anime y = new Anime();
y.setName("Gundam Seed");

insert(x);
insert(y);
list();
delete(x);
list();

insert(x);
x.setName("Gundam Seed Destiny");
update(x);
list();
}

private void update(Anime record) {
Transaction tx = null;
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
session.update(record);
tx.commit();
} catch(Exception re) {
if(tx != null && tx.isActive()) {
try {
tx.rollback();
} catch(HibernateException he) {
logger.debug("Unable to rollback");
}
}
logger.debug("No row updated");
}
}

private void delete(Anime record) {
Transaction tx = null;
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
session.delete(record);
tx.commit();
} catch(RuntimeException re) {
if(tx != null && tx.isActive()) {
try {
tx.rollback();
} catch(HibernateException he) {
logger.debug("Unable to rollback");
}
}
throw re;
}
}

@SuppressWarnings("unchecked")
private void list() {
Transaction tx = null;
Session session = SessionFactoryUtil.getInstance().getCurrentSession();
try {
tx = session.beginTransaction();
List x = session.createQuery("SELECT name FROM Anime").list();
System.out.println("Count: " + x.size());
for(Iterator i = x.iterator(); i.hasNext();) {
System.out.println(i.next());
}
tx.commit();
} catch(RuntimeException re) {
if(tx != null && tx.isActive()) {
try {
tx.rollback();
} catch(HibernateException he) {
logger.debug("Unable to rollback");
}
}
throw re;
}
}

private void insert(Anime record) {
Transaction tx = null;
Session session = SessionFactoryUtil.getInstance().getCurrentSession();

try {
tx = session.beginTransaction();
session.save(record);
tx.commit();
} catch(RuntimeException re) {
if(tx != null && tx.isActive()) {
try {
tx.rollback();
} catch(HibernateException he) {
logger.debug("Error rolling back.");
}
}
throw re;
}
}
}


That should do it :-D. Happy hibernating :-D.




- Hibernate With Infinispan Tutorial For Beginners
This tutorial is for developers who are just beginning to learn hibernate-search and trying to set up a demo project. Most of the codes are copied from the hibernate-search documentation: https://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/...

- Jdbc Provider Setting In Java For Postgresql, Mysql And Oracle
Below are the summary of connection settings for differenct jdbc provider: Database Connection Url Driver Class Hibernate Dialect Cache Provider Class PostgreSQL jdbc:postgresql://[host]:[port]/[db] org.postgresql.Driver org.hibernate.dialect.PostgreSQLDialect...

- How To Run Activiti In Glassfish/postgresql In Jta Mode
What you need: 1.) Glassfish 2.) Postgresql - make sure that max_transactions is set to at least 10. Otherwise you will encounter the no session error because by default the value is 0. 3.) Checkout travelexpenses from: https://svn.camunda.com/fox/demo/activiti-cdi/travelexpenses/trunk/...

- How To Send Jms Message To A Jms Queue
This tutorial requires that you have completed my previous tutorial on how to setup jms broker on glassfish: http://czetsuya-tech.blogspot.com/2012/06/how-to-setup-set-jms-factory-and-queue.html From the previous tutorial we will use the ff values: queue...

- Java.lang.nosuchmethodexception: Org.hibernate.validator.classvalidator
Note I'm using jboss-5.1.0.GA If you ever encounter the following error: Caused by: org.hibernate.AnnotationException: java.lang.NoSuchMethodException: org.hibernate.validator.ClassValidator.(java .lang.Class, java.util.ResourceBundle, org.hibernate.validator.MessageInterpolator,...



Tech-Today








.