hibernate入门小例子

昨天刚开始接触hibernate便被伤的彻底,连最简单的都不会配置,然后看书看网上的,要么是比较复杂,不适合刚入门的新手,要么太久了,代码有些地方不太正确

折磨到了今天才琢磨出一点,写这个帖子希望能够帮到像我一样的新手

#实验环境:myeclipse2013+mysql5.6.10+jdk1.7+hibernate 4.1

#目录结构:

#在mysql中新建一个名为hibernate的数据库

#首先,建立web应用,我用的是myeclispe2013,所以直接添加hibernate特性,如果用的是eclipse,则将下载的hibernate包中的lib目录下的required目录中的jar复制到应用中的lib目录下,然后buildpath.

接下来主要步骤:

1.修改src目录下的hibernate.cfg.xml,如果没有自动生成,则手动新建一个。修改如下

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

    <session-factory>
        <!-- 表示可动态修改hibernate属性文件 -->
        <property name="hbm2ddl.auto">update</property>
       <!-- 表示用户使用的数据库种类 -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <!-- 指定是否在控制台打印对应的SQL语句 -->
        <property name="show_sql">true</property>
       <!-- 链接数据库属性 -->
        <property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    
        <mapping resource="tbl/hibernate/bean/Person.hbm.xml"/>
    </session-factory>

</hibernate-configuration>

2.新建一个简单的POJO(普通java对象类) Person

 此处id用于被hibernate识别用于主键,相当于平时只有name属性的POJO

package tbl.hibernate.bean;

public class Person {
    private Integer id;    //id是标识符,被hibernate识别
    private String name;
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}

3.新建Person.hbm.xml,修改如下

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 <!-- 指定包,可不指定,但这样可以稍微减少代码量 -->
<hibernate-mapping package="tbl.hibernate.bean">
    <!-- 类名,如果上面未指定包,则此处需要在类之前将包写全,table对应数据库的表名 -->
    <class name="Person" table="person">
        <!--指定id为person类中的id,对应数据库表中的id列  -->
        <id name="id" column="id">
            <!-- 设置id为主键 -->
            <generator class="identity"></generator>
        </id>
        <!-- 同上 -->
        <property name="name" column="name"></property>
    </class>
</hibernate-mapping>

4.建立HibernateUtil工具类,myeclipse可自动右键生成,NEW-->Hibernate Session Factory

package tbl.hibernate.util;

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

/**
 * Configures and provides access to Hibernate sessions, tied to the
 * current thread of execution.  Follows the Thread Local Session
 * pattern, see {@link http://hibernate.org/42.html }.
 */
public class HibernateUtil {

    /** 
     * Location of hibernate.cfg.xml file.
     * Location should be on the classpath as Hibernate uses  
     * #resourceAsStream style lookup for its configuration file. 
     * The default classpath location of the hibernate config file is 
     * in the default package. Use #setConfigFile() to update 
     * the location of the configuration file for the current session.   
     */
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static org.hibernate.SessionFactory sessionFactory;
    
    private static Configuration configuration = new Configuration();
    private static ServiceRegistry serviceRegistry; 

    static {
        try {
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }
    private HibernateUtil() {
    }
    
    /**
     * Returns the ThreadLocal Session instance.  Lazy initialize
     * the <code>SessionFactory</code> if needed.
     *
     *  @return Session
     *  @throws HibernateException
     */
    public static Session getSession() throws HibernateException {
        Session session = (Session) threadLocal.get();

        if (session == null || !session.isOpen()) {
            if (sessionFactory == null) {
                rebuildSessionFactory();
            }
            session = (sessionFactory != null) ? sessionFactory.openSession()
                    : null;
            threadLocal.set(session);
        }

        return session;
    }

    /**
     *  Rebuild hibernate session factory
     *
     */
    public static void rebuildSessionFactory() {
        try {
            configuration.configure();
            serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        } catch (Exception e) {
            System.err.println("%%%% Error Creating SessionFactory %%%%");
            e.printStackTrace();
        }
    }

    /**
     *  Close the single hibernate session instance.
     *
     *  @throws HibernateException
     */
    public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

        if (session != null) {
            session.close();
        }
    }

    /**
     *  return session factory
     *
     */
    public static org.hibernate.SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    /**
     *  return hibernate configuration
     *
     */
    public static Configuration getConfiguration() {
        return configuration;
    }

}

5.最后一步,建立一个测试文件Person_test

package tbl.hibernate.domain;

import org.hibernate.Session;

import tbl.hibernate.bean.Person;
import tbl.hibernate.util.HibernateUtil;

public class Person_test {
    public static void main(String[] args) {
     //通过工具类获取Session Session session
= HibernateUtil.getSession();
     //开启事务 session.beginTransaction();
     //新建Person类,存入值 Person p
= new Person(); p.setName("Tom");
     //将p存入session session.save(p);
     //提交事务 session.getTransaction().commit();
     //关闭session session.close(); } }

#运行Person_test,如果没有报错,并且数据库中生成了一个person表,那么恭喜你,你成功了!

希望能够帮到大家,如果有什么疑问,可以评论,一起讨论。写的不对的也请大神指正,谢谢

原文地址:https://www.cnblogs.com/q812717031/p/3152299.html