残香渐逝
2018-05-12 12:02
采纳率: 100%
浏览 1.4k
已采纳

SSH框架Hibernate基于Spring自动生成的DAO怎样使用

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;
        }
    }
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • threenewbee 2018-05-12 12:09
    已采纳

    检查下配置,session没有正确加载一般是spring注入有问题。
    参考:https://blog.csdn.net/u014308482/article/details/53033832

    正告楼下抄袭本人回答的无耻之徒,本人坚持投诉到底,直到封号为止!

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • 残香渐逝 2018-05-13 08:19

    修改UserDAO

     package org.dao;
    
    import java.util.List;
    
    import org.hibernate.HibernateException;
    import org.hibernate.Query;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
    import org.hibernate.service.ServiceRegistry;
    import org.hibernate.service.ServiceRegistryBuilder;
    import org.springframework.context.ApplicationContext;
    import org.vo.User;
    
    public class UserDAO {
    
        private static Configuration cfg = new Configuration().configure();
        private static ServiceRegistry sr = new ServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).buildServiceRegistry();
        private static SessionFactory sessionFactory = cfg.buildSessionFactory(sr);
        private static Session session = sessionFactory.getCurrentSession();
    
        static {
            session.beginTransaction();
        }
    
        public boolean save(User user) {
            try {
                session.save(user);
                session.getTransaction().commit();
                return true;
            } catch (HibernateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
        }
    
        public boolean delete(User user) {
            try {
                session.delete(user);
                session.getTransaction().commit();
                return true;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
        }
    
        public List<?> findByUname(String name) {
            try {
                User user = new User();
                user.setUname(name);
                Query query = session.createQuery("from User where uname=?");
                query.setString(0, name);
                List<?> list = query.list();
                session.getTransaction().commit();
                return list;
            } catch (HibernateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return null;
            }
        }
    
        public boolean saveOrUpdate(User user) {
            try {
                session.saveOrUpdate(user);
                session.getTransaction().commit();
                return true;
            } catch (HibernateException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
        }
    
        public static UserDAO getFromApplicationContext(ApplicationContext ctx) {
            return (UserDAO) ctx.getBean("UserDAO");
        }
    }
    

    对于Hibernate4+Spring3这样就可以正常使用了,对于新手来说这样比较好,或者使用更高版本的Hibernate5以上,factoryManager在4和3版本中问题不少。
    对于说改配置的,看遍全网,基本还没有发现能够真正意义上解决问题。
    另外很少人使用自动生成的DAO,咨询一些软企经验丰富的高手,发现他们使用其他的一些工具生成更加完美的DAO、Action等系列

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题