新建我们的Dynamic Web Project,取名为"ssh_annotation”,配置Tomcat6.0的支持,打开MySQL,建立一个空数据库,取名为"ssh_annotation"。记得,要引进MySQL的JDBC驱动包mysql-connector-java-5.0.8-bin.jar。
在解压缩的hibernate-distribution-3.3.1.GA目录中,把hibernate.jar,和\lib\required\下的所用jar包引进到我们项目的lib目录下。
不知道用过Hibernate3.3开发的朋友会不会遇到过这样的问题:把上面的包都准备好的,开发Hibernate测试类时,会报Caused by: java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder 或者Caused by: java.lang.NoClassDefFoundError: org/apache/log4j/LogManager的错误。这是因为Hibernate3.3提供的jar包,缺少了slf4j-log4j12.jar这个包。解决办法是:在Hibernate的官方网站上下载hibernate-annotations-3.4.0.GA.zip,解压缩,把其\lib\下的slf4j-log4j12.jar引进我们项目的lib目录下。而我们引进这个jar包后,若我们没有引进log4j.jar的话,就会报java.lang.NoClassDefFoundError: org/apache/log4j/LogManager的错误,可能是slf4j-log4j12.jar要用调用log4j的类吧。我们也引进log4j.jar即行。 当然,hibernate-annotations-3.4.0.GA.zip 是我们开发Hibernate Annotation所要用到的,除以上面那些jar包外,我们还要引进其hibernate-annotations.jar,及其\lib\下的hibernate-commons-annotations.jar,ejb3-persistence.jar。好,暂时就这些,我们接下来需要用到哪些jar包时再引进。
好,第一步,来开发我们的实体类User。代码如下:
package com.rong.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="tb_user")
public class User {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(name="username", length=15)
private String username;
@Column(name="password", length=15)
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
简单解释一下吧:
@Entity定义User类为实体类,@Id定义该属性对应的列为主键,@GeneratedValue(strategy=GenerationType.IDENTITY)定义主键生成策略为Indentity,适用于MySQL和MS SQL等数据库。@Column(name="username", length=15)定义列名和取值长度。
当然,必要的XML配置文件还是要有的:
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/ssh_annotation</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- 数据库言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 将Session扔到线程里去处理 -->
<property name="current_session_context_class">thread</property>
<!-- 在控制台打印SQL语句 -->
<property name="show_sql">true</property>
<!-- 自动把实体类与属性映射成数据库中的表与列 -->
<property name="hbm2ddl.auto">update</property>
<!--
<mapping resource="com/rong/entity/User.hbm.xml"/>
-->
<!-- 在Hibernate中注册User实体类,区别于上面注释掉的resource写法 -->
<mapping class="com.rong.entity.User"/>
</session-factory>
</hibernate-configuration>
接下来,我们来开发一个包装器类,取名HibernateUtil,代码如下:
package test.rong.hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final String CONFIG_FILE = "conf/hibernate.cfg.xml";
private static final SessionFactory sessionFactory;
static {
try {
//用xxx.hbm.xml形式配置实体映射
//sessionFactory = new Configuration().configure().buildSessionFactory();
//用Annotation形式配置实体映射
//默认的hibernate.cfg.xml必须在项目的classes目录下 不然的话需要指定路径
//我在这里默认是我指定的路径优先 如果没有就在classes目录下寻找
String filePath = HibernateUtil.class.getResource("/") + CONFIG_FILE;
File file = new File(filePath.replace("file:/", ""));
if(file.exists()){
sessionFactory = new AnnotationConfiguration().configure(file).buildSessionFactory();
}else{
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
}
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
接下来,我们还要实现一个ServletContextListener,以便在web.xml初始化的时候调用hibernate配置文件
package test.rong.hibernate;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class HibernateListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent event) {
HibernateUtil.getSessionFactory(); // Just call the static initializer of that class
}
public void contextDestroyed(ServletContextEvent event) {
HibernateUtil.getSessionFactory().close(); // Free all resources
}
}
最后在web.xml里面加上
<listener>
<listener-class>org.mypackage.HibernateListener</listener-class>
</listener>
到这里,我们可以运行Tomcat,Hibernate会根据hbm2ddl.auto自动地把实体类与属性转变成数据库中的表与列。但这一步,要事先在数据库中建立一个名为"ssh_annotation"的空数据库。好了,看一下,你的数据库中是否有"tb_user"的表生成了?!
下面,我们来进行测试,下载最新版本的Junit4.0.jar,试一下感觉如何。当然,旧版本的应该也没问题的啦!写测试代码如下:
package test.rong.hibernate;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.junit.Before;
import org.junit.Test;
import com.rong.entity.User;
public class EntityTest {
private Session session;
@Before
public void initSession(){
this.session = HibernateUtil.getSessionFactory().openSession();
}
@Test //测试添加用户
public void testSave(){
session.beginTransaction();
User user = new User();
user.setUsername("rongxh7");
user.setPassword("blogjava");
session.save(user);
session.getTransaction().commit();
}
@Test //测试查询用户列表
@SuppressWarnings("unchecked")
public void testQuery(){
session.beginTransaction();
Query query = session.createQuery("from User u");
List<User> users = query.list();
for(Iterator<User> it = users.iterator() ; it.hasNext() ; ){
User user = it.next();
System.out.println("username = " + user.getUsername());
}
session.beginTransaction().commit();
}
@Test //测试查询单个用户
public void testGet(){
session.beginTransaction();
User user = (User)session.get(User.class, 1);
System.out.println("username = " + user.getUsername());
session.getTransaction().commit();
}
@Test //测试查询修改用户
public void testUpdate(){
session.beginTransaction();
User user = (User)session.load(User.class, 1);
user.setPassword("hello blogjava");
session.update(user);
session.getTransaction().commit();
}
@Test //测试删除用户
public void testDelete(){
session.beginTransaction();
session.delete(session.load(User.class, 1));
session.getTransaction().commit();
}
}
到此,我们的Hibernate Annotation开发完成了。
本文山寨 和原文有出入 转载自http://www.blogjava.net/rongxh7/archive/2009/03/23/261577.html