Hibernate Persistence Layer Getting Started Example

1. Create a new project and import the Hibernate jar package. and the connection package needed to connect to the database. For example: mysql-connector-java-5.1.28-bin.jar

2. Create com.huizhi.dao, com.huizhi.po, com.huizhi.utils, and com.huizhi.test packages under scr.

3. Create a new configuration file hibernate.cfg.xml under scr.
<?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>
		<!-- Configure Database Adapter -->
		<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- Configure database jdbc driver-->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- Configuration database connection string -->
		<property name="connection.url">jdbc:mysql://192.168.1.110:3306/hibernate</property>
		<!-- Configure database connection username-->
		<property name="connection.username">sa</property>
		<!-- Configure database connection user password-->
		<property name="connection.password">hainan</property>
		<!-- Whether to display the hibernate SQL statement -->
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>
		<!-- When the entity class is exported to the database, if there is a table processing method: hibernate.hbm2ddl.auto :(create-drop, create, update, validate) -->
		<property name="hbm2ddl.auto">update</property>
		
		<!-- Configure entity class mapping -->
		<mapping class="com.huizhi.po.User" />
		
	</session-factory>
</hibernate-configuration>


4. Add the entity class under the po package, and the mapping configuration file User.hbm.xml.
package com.huizhi.po;

public class User {
	
	private String USER_ID;
	
	private String USER_NAME;
	
	private String USER_PWD;

	public String getUSER_ID() {
		return USER_ID;
	}

	public void setUSER_ID(String uSER_ID) {
		USER_ID = uSER_ID;
	}

	public String getUSER_NAME() {
		return USER_NAME;
	}

	public void setUSER_NAME(String uSER_NAME) {
		USER_NAME = uSER_NAME;
	}

	public String getUSER_PWD() {
		return USER_PWD;
	}

	public void setUSER_PWD(String uSER_PWD) {
		USER_PWD = uSER_PWD;
	}
	
	
	
}


<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
	"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
	"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.huizhi.po.User">
	<class name="com.huizhi.po.User" table="USER_INFO">

		<id name="USER_ID">
			<column name="USER_ID" />
			<!-- Configure the primary key generation strategy-->
			<generator class="uuid" />
		</id>
		
		<property name="USER_NAME" column="USER_NAME" />
		<property name="USER_PWD" column="USER_PWD" />
	</class>
</hibernate-mapping>


5. Create a new HibernateUtil.java file under the utils package.
package com.huizhi.utils;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {
      /**
      * @return get the session factory
      */
       public static SessionFactory getSessionFactory()
       {
         //Read Hibernate's configuration file hibernamte.cfg.xml file
         Configuration cfg=new Configuration().configure();
         //Create a service registration builder object and load all configuration information through the configuration object
         ServiceRegistryBuilder regbulider=new ServiceRegistryBuilder().applySettings(cfg.getProperties());
         //create registration service
         ServiceRegistry sr=regbulider.buildServiceRegistry();
         //create session factory
         SessionFactory sessionFactory=cfg.buildSessionFactory(sr);
         
         return sessionFactory;
       }
       
      /**
      * @return get the session object
      */
       public static Session getSession()
       {
          return getSessionFactory().openSession();
       }
}


6. Create a new BaseDao.java file under the dao package.
package com.huizhi.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.huizhi.utils.HibernateUtil;

public class BaseDAO {
      /**
     * @param obj add data
     * @return
     */
      public static boolean add(Object obj)
      {
        Session session=null;
        Transaction tran=null;
        boolean result=false;
        try
        {
            session=HibernateUtil.getSession();
            tran=session.beginTransaction();
            session.save(obj);
            tran.commit();
            result=true;
        }
        catch (Exception e)
        {
           if(tran!=null)
           {
               //thing rolls back
               tran.rollback();
           }
        }
        finally
        {
            if(session!=null)
            {
                //Close the session
                session.close();
            }
        }
        return result;
      }
      
      /**
     * @return update data
     * The parameter is the modified primary key id object
     */
    public static boolean update(Object object)
      {
            Session session=null;
            Transaction tran=null;
            boolean result=false;
            try
            {
                session=HibernateUtil.getSession();
                tran=session.beginTransaction();
                session.update(object);
                tran.commit();
                result=true;
            }
            catch (Exception e)
            {
               if(tran!=null)
               {
                   //thing rolls back
                   tran.rollback();
               }
            }
            finally
            {
                if(session!=null)
                {
                    //Close the session
                    session.close();
                }
            }
            return result;
          }
         
      /**
     * @param c
     * @param id Query a piece of data based on the id number of the primary key
     * @return
     */
      public static Object get(Class<?> c,int id)
      {
            Session session=null;
            Object object=null;
            try
            {
                session=HibernateUtil.getSession();
                object=session.get(c,id);
            }
            catch (Exception e)
            {
            }
            finally
            {
                if(session!=null)
                {
                    //Close the session
                    session.close();
                }
            }
            return object;
      }

      /**
     * @param obj
     * @return delete data
     */
    public static boolean delete(Object obj)
      {
            Session session=null;
            Transaction tran=null;
            boolean result=false;
            try
            {
                session=HibernateUtil.getSession();
                tran=session.beginTransaction();
                session.delete(obj);
                tran.commit();
                result=true;
            }
            catch (Exception e)
            {
               if(tran!=null)
               {
                   //thing rolls back
                   tran.rollback();
               }
            }
            finally
            {
                if(session!=null)
                {
                    //Close the session
                    session.close();
                }
            }
            return result;
      }


      /**
     * @param <T> query multiple records
     * @param sql sql statement
     * @param param parameter array
     * @return
     */
     @SuppressWarnings("unchecked")
    public static <T> List<T> query(String sql,String[] param)
      {

          List<T> list=new ArrayList<T>();
          Session session=null;
           try
            {
                session=HibernateUtil.getSession();
                Query query=session.createQuery(sql);
                if(param!=null)
                {
                    for(int i=0;i<param.length;i++)
                    {
                        query.setString(i,param[i]);    
                    }
                }
                list=query.list();
            }
            catch (Exception e)
            {
            	System.out.println(e.getMessage());
            }
            finally
            {
                if(session!=null)
                {
                    session.close();
                }
            }
          return list;
      }
      /**
     * @param sql
     * @param param query a single record
     * @return
     */
    public static Object queryOne(String sql,String[] param)
      {
          Object object=null;
          Session session=null;
           try
            {
                session=HibernateUtil.getSession();
                Query query=session.createQuery(sql);
                if(param!=null)
                {
                    for(int i=0;i<param.length;i++)
                    {
                        query.setString(0,param[i]);    
                    }
                    object=query.uniqueResult();
                }
            }
            catch (Exception e)
            {
            }
            finally
            {
                if(session!=null)
                {
                    session.close();
                }
            }
          return object;
      }
    /**
     * @param <T>
     * @param sql
     * @param param
     * @param page
     * @param you
     * @return implement paging query
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> queryByPage(String sql,String[] param,int page,int size)
      {
          List<T> list=new ArrayList<T>();
          Session session=null;
           try
            {
                session=HibernateUtil.getSession();
                Query query=session.createQuery(sql);
                if(param!=null)
                {
                    for(int i=0;i<param.length;i++)
                    {
                        query.setString(i,param[i]);    
                    }
                }
                // filter the number of bars
                query.setFirstResult((page-1)*size);
                query.setMaxResults(size);
                list=query.list();
            }
            catch (Exception e)
            {
            }
            finally
            {
                if(session!=null)
                {
                    session.close();
                }
            }
          return list;
      }
    /**
     * @param hql
     * @param for
     * @return returns the number of data
     */
    public static int getCount(String hql, String[] pras) {
        int resu = 0;
        Session s = null;
        try {
            s = HibernateUtil.getSession();
            Query q = s.createQuery(hql);
            if (pras != null) {
                for (int i = 0; i < pras.length; i++) {
                    q.setString(i, pras[i]);
                }
            }
            resu = Integer.valueOf(q.iterate().next().toString());
        } catch (Exception e) {
            e.printStackTrace ();
        } finally {
            if (s != null)
                s.close();
        }
        return resu;
    }
     

}


7. Create a new test.java test file under the test package for testing.
package com.huizhi.test;

import java.util.List;
import com.huizhi.dao.BaseDAO;
import com.huizhi.po.User;

public class test {

	public static void main(String[] args) {
		//Add user
		User user = new User();
		user.setUSER_NAME("Sun Wukong");
		user.setUSER_PWD("admin");
		BaseDAO.add(user);
	
		//Paging query
	    List<User>list = BaseDAO.queryByPage("FROM User WHERE USER_PWD=?", new String[]{"admin"}, 1, 2);
	    for (User user2 : list) {
			System.out.println("Username:"+user2.getUSER_NAME() +";Password:"+user2.getUSER_PWD());
		}
	    
	}

}




———————————————————————————————————
The way of annotation: the
entity class is modified to
package com.huizhi.po;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="USER_INFO")
public class User {
	
	private int USER_ID;
	
	private String USER_NAME;
	
	private String USER_PWD;

	@Id
	@Column(name = "USER_ID",nullable=false)
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public int getUSER_ID() {
		return USER_ID;
	}

	public void setUSER_ID(int uSER_ID) {
		USER_ID = uSER_ID;
	}

	@Column(name = "USER_NAME", nullable=false, length = 100)
	public String getUSER_NAME() {
		return USER_NAME;
	}

	public void setUSER_NAME(String uSER_NAME) {
		USER_NAME = uSER_NAME;
	}

	@Column(name = "USER_PWD",nullable=false , length = 32)
	public String getUSER_PWD() {
		return USER_PWD;
	}

	public void setUSER_PWD(String uSER_PWD) {
		USER_PWD = uSER_PWD;
	}	
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326215511&siteId=291194637