hibernate Step By Step (一)

hibernate Step By Step (1)
Hibernate的第一个例子,用hibernate3.0  数据库用Hsql(因为运行起来简单)
描述我要达到的目的:完成一个最简单的功能:在表User中插入一条记录。

1,新建工程,添加Hibernate支持,可以用Myeclipse自带的加入Hibernate支持功能。不过这里我想自己引入包:<url>http://ikeel.iteye.com/admin/blogs/174641</url>可以参考这篇文章。
然后为了使用Hsql还要引入hsql.jar
2,有这样几个配置文件:

log4j.properties;
hibernate.cfg.xml;
xxx.hbm.xml;

分别说明:
log4j:位于src根目录下,不用多说,但是如果不加入这个配置会报警告的。并且也看不到执行过程中的日志记录。
内容:

log4j.rootLogger=WARN, Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=(%r ms) [%t] %-5p: %c#%M %x: %m%n

log4j.logger.com.genuitec.eclipse.sqlexplorer=DEBUG
log4j.logger.org.apache=WARN
log4j.logger.org.hibernate=WARN


hibernate.cfg.xml:
位于src根目录下。
<?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="connection.driver_class">
org.hsqldb.jdbcDriver
</property>
<property name="connection.url">
jdbc:hsqldb:hsql://localhost
</property>
<property name="connection.username">SA</property>
<property name="connection.password"></property>

<property name="dialect">
org.hibernate.dialect.HSQLDialect
</property>
<property name="show_sql">true</property>
<property name="connection.pool_size">3</property>

<property name="hbm2ddl.auto">create</property>
<property name="current_session_context_class">thread</property>


<mapping resource="dian/ikeel/hibernate/beans/Users.hbm.xml" />

</session-factory>

</hibernate-configuration>


对这个配置文件,有几点需要说明的,就是DTD的引入,可以采用本地文件系统的,也可以采用上面所写的网络地址。
注意:<property name="current_session_context_class">thread</property>
如果缺少这一句时会报错:No CurrentSessionContext configured!

xxx.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>

<class name="dian.ikeel.hibernate.beans.Users" table="User">
<id name="id" column="userid">
<generator class="native"></generator>
</id>
<property name="username" column="name"></property>

<property name="password" column="pwd"></property>
</class>
</hibernate-mapping>


对应的Users.java内容如下:
package dian.ikeel.hibernate.beans;


public class Users {

private long id;
private String username;
private String password;

public Users()
{}

   gets  &  sets ...
}



attention:
<class name="dian.ikeel.hibernate.beans.Users" table="User">需要指定包名。如果不指定就会报错:Could not read mappings from resource: Users.hbm.xml

2,到目前基本的配置已经完成,开始使用操作了。

package dian.ikeel.hibernate.BLL;



import org.hibernate.Session;


import dian.ikeel.hibernate.beans.*;
import dian.ikeel.hibernate.util.hibernateutil.*;
import dian.ikeel.hibernate.util.SessionFactory.*;

public class Entry {

public  static void main(String[] args)
{

Session  session=HibernateSessionFactory.getSessionFactory().getCurrentSession();
     session.beginTransaction();
      Users  user=new Users();
      user.setUsername("ikeel");
      user.setPassword("ikeel");
      session.save(user);
      session.getTransaction().commit();
      System.out.println("KKKKKK");
           
     
}



其中用到一个Util类:HibernateSessionFactory:

package dian.ikeel.hibernate.util.SessionFactory;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;


public class HibernateSessionFactory {

        private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

static {
    try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
    }
    private HibernateSessionFactory() {
    }

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

public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err
.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}

     public static void closeSession() throws HibernateException {
        Session session = (Session) threadLocal.get();
        threadLocal.set(null);

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

public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}

public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration() {
return configuration;
}

}
 

}

3,OK了,可以开始使用了,在命令行下进入到 Project/HibernateStudy/data 目录下,先建立data目录吧。然后执行:  java -classpath ..\lib\hsql.jar org.hsqldb.Server 数据库就启动了。
开始Run Entry,可以看到都发生了什么.....


4,接下来,我不想用xxx.hbm.xml了,我想试试annotation ....