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

 

一、下载所需要的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>

 

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

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

}



}

 

查询结果:

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

附二:目录结构:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值