Hibernate入门-搭建框架实现基本的增删改查

来源:互联网 发布:窃听风暴知乎 编辑:程序博客网 时间:2024/05/21 05:44

一、下载所需要的jar

首先是必须有的数据库驱动包,数据库我用的是MySQL,记得导入对应的jar包
   Hibernate需要的包不少,这里留个连接:http://hibernate.org/orm/downloads/,下载后把lib里面的包都导入就可以了

二、开始搭建

注:这个项目的源码我会在文末放出链接,需要的可以去下载

新建一个Web工程,把jar包都放在WebRoot/WEB-INF/lib底下
src底下创建核心配置文件,起名为hibernate.cfg.xml,最好都起这个名字,因为hibernate里面configure()方法会自动加载类目录下的hibernate.cfg.xml这个文件
开始写配置:

<!DOCTYPE hibernate-configuration PUBLIC

    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"

    "http://www.hibernate.org/dtd/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:///hibernate</property>  

        <property name="hibernate.connection.username">root</property>  

        <property name="hibernate.connection.password">adminadminadmin</property>

        

        <!-- 输出底层sql语句 -->  

        <property name="hibernate.show_sql">true</property>  

        <!-- 输出底层sql语句格式 -->    

        <property name="hibernate.format_sql">true</property>  

        

        <!-- hibernate更新数据库的方法

            create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这就是导致数据库表数据丢失的一个重要原因。

create-drop :每次加载hibernate时根据model类生成表,但是sessionFactory一关闭,表就自动删除。

update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。

validate::启动时验证现有schema与你配置的hibernate是否一致,如果不一致就抛出异常,并不做更新。  

        -->  

        <property name="hibernate.hbm2ddl.auto">update</property>  

        <!-- 配置数据库方言  

           mysql里面实现分页 关键字 limit,只能使用mysql里面  

           oracle数据库,实现分页rownum  

           hibernate框架识别不同数据库的自己特有的语句  

         -->

        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!- 映射文件 ->

     <mapping resource="com/test/bean/User.hbm.xml"/>

    </session-factory>  

</hibernate-configuration>

 

核心配置写完后开始写实体类:

 

package com.test.bean;

 

 

public class User {

private int id;

     private String name;

//get和set方法

}

<?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>  

    <class name="com.test.bean.User" table="t_user">  

        <id name="id" column="id" type="java.lang.Integer">  

            <generator class="identity"></generator>  

        </id>  

        <property name="name" column="name" type="string"></property>

    </class>  

</hibernate-mapping>

 


然后写实体类的映射文件:


<?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>  

    <class name="com.test.bean.User" table="t_user">  

        <id name="id" column="id" type="java.lang.Integer">  

            <generator class="identity"></generator>  

        </id>  

        <property name="name" column="name" type="string"></property>

    </class>  

</hibernate-mapping>

 

写到这里基本配置都完成了,最后就是要写业务了,做个简单的增删改查:

 

package com.test.habernate;

 

import java.io.Serializable;

 

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.SessionFactory;  

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;  

  

public class HibernateUtils {  

  

    static Configuration cfg = null;  

    static SessionFactory sessionFactory = null;  

    //静态代码块实现  

    static {  

        //加载核心配置文件  

        cfg = new Configuration();  

        try {

         //这个方法会自动加载类目录下的hibernate.cfg.xml这个文件

cfg.configure();

} catch (HibernateException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}  

        sessionFactory = cfg.buildSessionFactory();  

    }  

      

    //提供方法返回sessionFactory  

    public static SessionFactory getSessionFactory() {  

        return sessionFactory;  

    }  

    

    //提供方法返回Session

    public static Session getSession(){

     return sessionFactory.openSession();

    }

    

    //增加

    public static void add(Object obj){

     Session session = null;  

        Transaction tx = null;  

        try {  

            session = HibernateUtils.getSession();  

            tx = session.beginTransaction();  

            session.save(obj);  

            tx.commit();  

        } catch(Exception e){

         e.printStackTrace();

        } finally{

         if(session!=null){

         session.close();

         }

        }

    }

    

    //删除

    public static void delete(Object obj){

     Session session = null;  

        Transaction tx = null;  

        try {  

            session = HibernateUtils.getSession();  

            tx = session.beginTransaction();  

            session.delete(obj);  

            tx.commit();  

        } catch(Exception e){

         e.printStackTrace();

        } finally{

         if(session!=null){

         session.close();

         }

        }

    }

    

    //修改

    public static void update(Object obj){  

        Session session = null;  

        Transaction tx = null;  

        try {  

            session = HibernateUtils.getSession();  

            tx = session.beginTransaction();  

            session.update(obj);  

            tx.commit();  

        } catch(Exception e){

         e.printStackTrace();

        } finally{

         if(session!=null){

         session.close();

         }

        }

    }  

    

    //查询

    public static Object Select(Class<?> cls,Serializable id){

     Session session = null;

     try {

     session = HibernateUtils.getSession();  

            Object obj = session.get(cls, id);

            return obj;

        } catch(Exception e){

         e.printStackTrace();

        } finally{

         if(session!=null){

         session.close();

         }

        }

return null;

    }

}  

 

到这里差不多是写完了,接下来写个Main跑一下看看能不能用的,这里我就试下查询和修改:

 

package com.test.test;

 

import com.test.bean.User;

import com.test.habernate.HibernateUtils;

 

public class Test {

public static void main(String[] args) {

        User user = new User();

        user.setId(6);

        System.out.println(HibernateUtils.Select(User.class,user.getId()));//查询

        user.setName("小00");

        HibernateUtils.update(user);//修改

        System.out.println(user);

}

 

}

 

查询结果:


附一:项目源码:点击这里下载

附二:目录结构: