一:log
Hibernate自带的jar包用的是slf-api,用这个api再加上一个适配器,就能用原来的log4j记录日志
用的加包是:
1.slf4j-api-1.6.1.jar(Hibernate带的)
2.slf4j-log4j12-1.6.1.jar(slf4j-1.6.1里提供的适配器)
3.log4j-1.2.17.jar(原来的log4j)
4.还要加上一个配置文件log4j.properties,拷过来直接用就行(在位置是:hibernate-release-4.1.6.Final\project\etc\log4j.properties)
二:单例辅助类
辅助类
把文档中提供的类改了一下,改用AnnotationConfiguration()
package org.hibernate.tutorial.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try {
// Create the SessionFactory from hibernate.cfg.xml
return new AnnotationConfiguration().configure().buildSessionFactory();
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
JUnit测试插入
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Teacher t = new Teacher();
t.setTeacherid(200);
t.setName("李四");
t.setAge(0);
t.setBirthday(new Date());
session.save(t);
session.getTransaction().commit();
HibernateUtil.getSessionFactory().close();
JUnit测试查询
Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();
session2.beginTransaction();
List<Teacher> result = session2.createQuery("from Teacher").list();//此行的Event指的是对应的类名,而不是数据表的名字。
Iterator it = result.iterator();
Teacher value = null;
while (it.hasNext())
{
value = (Teacher)it.next();
System.out.println(value.getTeacherid());
System.out.println(value.getName());
System.out.println(value.getAge());
System.out.println(value.getBirthday());
}
session2.getTransaction().commit();
HibernateUtil.getSessionFactory().close();