no

Introduction to Hibernate

Since, I've always been using different database sometimes I get confused how to implement the others. Like hibernate, where the configu...

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.

Related

java-persistence 3557958654411624933

Post a Comment Default Comments

item