hibernate demo 搭建

本文介绍了一个基于Hibernate框架的用户管理系统的实现过程,包括User类的设计、XML映射文件的配置、DAO接口及其实现,以及Hibernate工具类的编写。

User 接口:

public class User implements java.io.Serializable {

    private int id;
    private String name;
    private String password;
    private String type;

    User()
    {

    }

    public int getId()
    {
        return this.id;
    }
    
    public void setId(int id)
    {
        this.id = id;
    }
    
    public void setName(String name)
    {
        this.name = name;
    }
    
    public String getName()
    {
        return this.name;
    }
    
    public void setPassword(String password)
    {
        this.password =password;
    }
    
    public String getPassword()
    {
        return this.password;
    }
    
    public void setType(String type)
    {
        this.type = type;
    }
    
    public String getType()
    {
        return this.type;
    }
}

User.hbm.xml 映射文件


<?xml version="1.0" encoding="UTF-8">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<!-- name 指定持久化类名 table 指定数据表-->
<class name="org.hibernate.entity.User" table="USER">
<!--将数据表和bean 映射对应起来-->
<id name="id" type="java.lang.Interger" column="USER_ID">
<generator class="increment">
</id>

<property name="name" type="java.lang.String" column="NAME" length="20">
</property>

<property name="password" type="java.lang.String" column="NAME" length="12">
</property>

<property name="type" type="java.lang.String" column="TYPE" length="6">
</property>
</class>
</hibernate-mapping>

hibernate.cfg.xml  配置文件

<?xml version="1.0" encoding="UTF-8">
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Configration DTD3.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>
<!--数据库url->


<property name="hibernate.connection.url" >
jdbc:mysql://localhost:3306/mysqldb
</property>

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

<property name="hibernate.connection.password" >123456</property>
<property name="hibernate.connection.pool_size" >1</property>
<property name="dialect" >org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql" >true</property>
<!--列出所有映射文件-->
<mapping resource="org/hibernate/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>


UserADO 接口类:


public interface UserDAO {
    
     void save(User user);
    
     User findById(int id);
    
     void delete(User user);
    
     void update(User user);
}


H会bernateUtil实现类:


public class HibernateUtil{

    private static SessionFactory sessionFactory;

    private static final ThreadLocal<Session> threadLocal
            = new ThreadLocal<Session>();


    static {

        try{

            Configuration cfg = new Configuration().configure();

            sessionFactory = cfg.buildSessionFactory();

        }
        catch (Throwable ex)
        {
            throew new ExceptionInInitializerError(ex);
        }
    }

    // 获得sessionfactory实例
    public static SessionFactory getSessionFactory()
    {
        return sessionFactory;
    }

    public static Sesstion getSession() throws HibernateExcaption
    {
        Session session = (Session) threadLocal.get();
        if(session == null || !session.isOpen())
        {
            if(sessionFactory == null)
            {
                rebuildSesstionFactory();
            }

            session = (sessionFactory != null)? sessionFactory.openSession():null;

            threadLocal.set(session);
        }

        return session;
    }


    public staitc void closeSession() throws HibernateExcaption
    {
        Session session = (Session) threadLocal.get();
        threadLocal.setnull();
        if(session == null ) {

            sesstion.close();
        }

    }


    public static void rebuildSesstionFactory()
    {
        try
        {
             confuguration.confugure.(/hibernate.cfg.xml);
            sessionFactory configuration.buildSessionFactory();
        }
        catch(Exception e)
        {
            System.err.println("error ncreate session factory.");
            e.printStackTrace();
        }
    }


 public static void shutdown()
 {
     getSessionFactory().close();
 }



}



UserADOImpl 实现类:

public class UserADOImpl implements UserDAO{

    public void save(User user){

        Session session = HibernateUtil.getSession();
        Transaction tx =session.beginTransaction();

        try
        {
            session.save(user);
            tx.commit();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            tx.rollback();
        }
        finally {
            HibernateUtil.closeSession();
        }
    }


    public void delete(User user){

        Session session = HibernateUtil.getSession();
        Transaction tx =session.beginTransaction();

        try
        {
            session.delete(user);
            tx.commit();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            tx.rollback();
        }
        finally {
            HibernateUtil.closeSession();
        }
    }


    public void update(User user){

        Session session = HibernateUtil.getSession();
        Transaction tx =session.beginTransaction();

        try
        {
            session.update(user);
            tx.commit();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            tx.rollback();
        }
        finally {
            HibernateUtil.closeSession();
        }
    }


    public User findByyId(int id){

        User user = null;

        Session session = HibernateUtil.getSession();
        Transaction tx =session.beginTransaction();

        try
        {
            user = session.get(User.class, id);
            tx.commit();
        }
        catch(Exception e)
        {
            e.printStackTrace();
            tx.rollback();
        }
        finally {
            HibernateUtil.closeSession();
        }

        return user;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值