applicantContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" xmlns:tx="http://www.springframework.org/schema/tx">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="UserDAO" class="org.dao.UserDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
</beans>
Hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/
</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="myeclipse.connection.profile">mysql</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="cache.use_query_cache">true</property>
<property name="cache.provider_class">org.hibernate.cache.HashtableCacheProvider</property>
<property name="cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<property name="current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</property>
<mapping resource="org/vo/User.hbm.xml" />
</session-factory>
</hibernate-configuration>
UserDAO类
public class UserDAO {
private static final Logger log = LoggerFactory.getLogger(UserDAO.class);
// property constants
public static final String UNAME = "uname";
public static final String PASSWORD = "password";
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
protected void initDao() {
// do nothing
}
public void save(User transientInstance) {
log.debug("saving User instance");
try {
getCurrentSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}
public void delete(User persistentInstance) {
log.debug("deleting User instance");
try {
getCurrentSession().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}
public User findById(java.lang.Integer id) {
log.debug("getting User instance with id: " + id);
try {
User instance = (User) getCurrentSession().get("org.vo.User", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
public List<?> findByExample(User instance) {
log.debug("finding User instance by example");
try {
List<?> results = getCurrentSession().createCriteria("org.vo.User")
.add(Example.create(instance)).list();
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}
public List<?> findByProperty(String propertyName, Object value) {
log.debug("finding User instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from User as model where model."
+ propertyName + "= ?";
Query queryObject = getCurrentSession().createQuery(queryString);
queryObject.setParameter(0, value);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}
public List<?> findByUname(Object uname) {
return findByProperty(UNAME, uname);
}
public List<?> findByPassword(Object password) {
return findByProperty(PASSWORD, password);
}
public List<?> findAll() {
log.debug("finding all User instances");
try {
String queryString = "from User";
Query queryObject = getCurrentSession().createQuery(queryString);
return queryObject.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
public User merge(User detachedInstance) {
log.debug("merging User instance");
try {
User result = (User) getCurrentSession().merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public void attachDirty(User instance) {
log.debug("attaching dirty User instance");
try {
getCurrentSession().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public void attachClean(User instance) {
log.debug("attaching clean User instance");
try {
getCurrentSession().buildLockRequest(LockOptions.NONE).lock(
instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}
public static UserDAO getFromApplicationContext(ApplicationContext ctx) {
return (UserDAO) ctx.getBean("UserDAO");
}
}
HibernateSessionFactory类
public class HibernateSessionFactory {
/**
* 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 final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* 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();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} 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 hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
测试类
package org.action;
import org.dao.UserDAO;
import org.vo.User;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Session session = HibernateSessionFactory.getSession();
// session.beginTransaction();
// 插入数据
// session.save(new User("大傻", "123"));
// 通过id查询数据
// User user = (User) session.load(User.class, 1);
// System.out.println(user.getPassword());
// 通过id查找并删除数据
// User user = (User) session.get(User.class, 8);
// session.delete(user);
// 通过id查找并修改数据
// User user = (User) session.load(User.class, 9);
// user.setPassword("999999");
// session.saveOrUpdate(user);
//
UserDAO userDAO = new UserDAO();
User user = new User("Jone", "111111");
userDAO.save(user);
// session.getTransaction().commit();
// session.close();
}
}
错误提示
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" java.lang.NullPointerException
at org.dao.UserDAO.getCurrentSession(UserDAO.java:41)
at org.dao.UserDAO.save(UserDAO.java:51)
at org.action.Test.main(Test.java:40)
第一行指向
UserDAO的private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
第二行错误指向
public void save(User transientInstance) {
log.debug("saving User instance");
try {
# getCurrentSession().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}