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>();
private static 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) {
Session session=AnnotationSessionFactory.getSessionFactory().getCurrentSession();

session.beginTransaction();

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

}


6,这样就算是最简单的Annotation 的Demo运行通过了。再去研究一下某些步骤是不是一定得那么做。
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。、可私 6信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 、可私信6博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 、可私信6博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值