hustlong 发表于 2013-1-14 23:48:44

Hibernate Step By Step (2)

考虑把通过xxx.hbm.xml转换为用Annotation从而省去配置文件。

首先假定已经可以在hbm.xml配置方式下运行成功 ,Step by step 1中已经描述。接下来需要在原来的方案上的改变如下:

1,首先,引入包,在保证hbm.xml方式运行的包的基础上,还需要:ejb3-persistence.jar(不要以为它是EJB的专用了),hibernate-annotation.jar。如果你用myeclipse开发,在hibernate相关目录下都可以找到的。
这一步有一些需要特别注意的地方:版本问题。因为我因为这个问题碰到过麻烦。下面也简单的介绍一下。
hibernate-annotation.jar 用的3.2.0.CR2版本,是比较新的版本了。
开始时hibernate我是用的hibernate-3.2.5版本的。
于是我把hibernate3.2.5换作了3.1 ,又发现另外一些类比如NativeSqlQueryReurn找不到...
最后再尝试用hibernate3.2.0.cr4 ,终于看到了我想要的。所以在这一步要比较小心。

其中一步我发现会报如下错误:SqlresultsetMappings Not found 。解决方法是引入Java EE 5的库。后来发现,如果引入了Java EE 5的库以后,就不用再引入ejb3-persistence.jar了 。因为Java EE 5已经把这个部分包含了,不再是EJB独有的了。

2,要用到的库文件就这些了,接下来开始写配置文件(Hibernate.cfg.xml这个配置还是需要的)。
hibernate.cfg.xml和用hbm.xml方式的区别是,mapping字段不再用resource,而改用 class=Myclass.
内容如下:
<?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="connection.pool_size">3</property>
<property name="show_sql">true</property>

<property name="hbm2ddl.auto">create</property>
<property name="current_session_context_class">thread</property>
<mapping class="dian.ikeel.annotation.Picture"/>


</session-factory>
</hibernate-configuration>



3,开始写Java类了,注意要用到Annotation的:

package dian.ikeel.annotation;

import javax.persistence.*;
import org.hibernate.annotations.AccessType;

@Entity
@Table(name="Pics")
@AccessType("property")

public class Picture {


private long picid;
private String picname;
private int picsize;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public long getPicid() {
return picid;
}

public void setPicid(long picid) {
this.picid = picid;
}
public String getPicname() {
return picname;
}
public void setPicname(String picname) {
this.picname = picname;
}
public int getPicsize() {
return picsize;
}
public void setPicsize(int picsize) {
this.picsize = picsize;
}




}


我就不详细解释每个标注的意思了。


4,下面该关心如何或得SessionFactory了,跟以前的方式的区别只有一点点,我们用到了AnnotationConfiguration;

代码如下:

package dian.ikeel.hibernate.util.SessionFactory;

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



/**
* 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 AnnotationSessionFactory {

    /**
   * 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 String CONFIG_FILE_LOCATION = "/annotationhibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    privatestatic AnnotationConfiguration configuration = new AnnotationConfiguration();
    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.getLocalizedMessage());
e.printStackTrace();
}
    }
   

/**
   * 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(configFile);
sessionFactory = configuration.buildSessionFactory();
} 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 session factory
   *
   *session factory will be rebuilded in the next call
   */
public static void setConfigFile(String configFile) {
AnnotationSessionFactory.configFile = configFile;
sessionFactory = null;
}

/**
   *return hibernate configuration
   *
   */
public static AnnotationConfiguration getConfiguration() {
return configuration;
}

}



5,接下来,启动数据库,我用的是hsql。然后给一个入口点就OK了。

最简单的入口函数:
package dian.ikeel.hibernate.BLL;

import org.hibernate.Session;

import dian.ikeel.annotation.Picture;
import dian.ikeel.hibernate.util.SessionFactory.*;
import org.hibernate.cfg.AnnotationConfiguration;;
public class AnnotationEntry {

/**
* @param args
*/
public static void main(String[] args) {
Sessionsession=AnnotationSessionFactory.getSessionFactory().getCurrentSession();

session.beginTransaction();

      Picturepic=new Picture();
       pic.setPicname("heat3");
       pic.setPicsize(123);
       session.save(pic);
      session.getTransaction().commit();
      System.out.println("AnnotationEntry excuted");
}

}


6,这样就算是最简单的Annotation 的Demo运行通过了。再去研究一下某些步骤是不是一定得那么做。
页: [1]
查看完整版本: Hibernate Step By Step (2)