Hibernate 持久层入门实例

朝军 2016-01-25

1、新建一个项目,导入Hibernate的jar包。和需要连接到数据库的连接包。例如:mysql-connector-java-5.1.28-bin.jar

2、在scr下创建com.huizhi.dao包、com.huizhi.po包、com.huizhi.utils包、com.huizhi.test包。

3、在scr下新建一个配置文件hibernate.cfg.xml。

<?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="dialect">org.hibernate.dialect.MySQLDialect</property>
		<!-- 配置数据库jdbc驱动 -->
		<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
		<!-- 配置数据库连接串 -->
		<property name="connection.url">jdbc:mysql://192.168.1.110:3306/hibernate</property>
		<!-- 配置数据库连接用户名 -->
		<property name="connection.username">sa</property>
		<!-- 配置数据库连接用户密码 -->
		<property name="connection.password">hainan</property>
		<!-- 是否显示hibernate的SQL语句 -->
		<property name="show_sql">true</property>
		<property name="format_sql">true</property>
		<!-- 实体类导出至数据库时,如果存在的表处理方式: hibernate.hbm2ddl.auto :(create-drop、create、update、validate) -->
		<property name="hbm2ddl.auto">update</property>
		
		<!-- 配置实体类映射 -->
		<mapping class="com.huizhi.po.User" />
		
	</session-factory>
</hibernate-configuration>

4、在po包下加入实体类,和映射配置文件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" />
			<!-- 配置主键生成策略 -->
			<generator class="uuid" />
		</id>
		
		<property name="USER_NAME" column="USER_NAME" />
		<property name="USER_PWD" column="USER_PWD" />
	</class>
</hibernate-mapping>

5、在utils包下新建HibernateUtil.java文件。

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 获取会话工厂
      */
       public static SessionFactory getSessionFactory()
       {
         //读取Hibernate的配置文件  hibernamte.cfg.xml文件
         Configuration cfg=new Configuration().configure();
         //创建服务注册构建器对象,通过配置对象中加载所有的配置信息
         ServiceRegistryBuilder regbulider=new ServiceRegistryBuilder().applySettings(cfg.getProperties());
         //创建注册服务
         ServiceRegistry sr=regbulider.buildServiceRegistry();
         //创建会话工厂
         SessionFactory sessionFactory=cfg.buildSessionFactory(sr);
         
         return sessionFactory;
       }
       
      /**
      * @return 获取会话对象
      */
       public static Session getSession()
       {
          return getSessionFactory().openSession();
       }
}

6、在dao包下新建BaseDao.java文件。

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 添加数据
     * @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)
           {
               //事物回滚
               tran.rollback();
           }
        }
        finally
        {
            if(session!=null)
            {
                //关闭session
                session.close();
            }
        }
        return result;
      }
      
      /**
     * @return 更新数据 
     * 参数为修改的主键id对象
     */
    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)
               {
                   //事物回滚
                   tran.rollback();
               }
            }
            finally
            {
                if(session!=null)
                {
                    //关闭session
                    session.close();
                }
            }
            return result;
          }
         
      /**
     * @param c
     * @param id  查询一条数据根据主键的id号
     * @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)
                {
                    //关闭session
                    session.close();
                }
            }
            return object;
      }

      /**
     * @param obj
     * @return 删除数据
     */
    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)
               {
                   //事物回滚
                   tran.rollback();
               }
            }
            finally
            {
                if(session!=null)
                {
                    //关闭session
                    session.close();
                }
            }
            return result;
      }


      /**
     * @param <T> 查询多条记录
     * @param sql  sql语句
     * @param param 参数数组
     * @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 查询单条记录
     * @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 size
     * @return 实现分页查询
     */
    @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]);    
                    }
                }
                //筛选条数
                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 pras
     * @return返回数据个数
     */
    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、在test包下新建test.java测试文件进行测试。

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) {
		//添加用户
		User user = new User();
		user.setUSER_NAME("孙悟空");
		user.setUSER_PWD("admin");
		BaseDAO.add(user);
	
		//分页查询
	    List<User>list = BaseDAO.queryByPage("FROM User WHERE USER_PWD=?", new String[]{"admin"}, 1, 2);
	    for (User user2 : list) {
			System.out.println("用户名:"+user2.getUSER_NAME() +";密码:"+user2.getUSER_PWD());
		}
	    
	}

}

——————————————————————————————————

注解的方式:

实体类修改为

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;
	}	
}

相关推荐

LetonLIU / 0评论 2020-05-29
东方咖啡屋 / 0评论 2020-01-06