public void save(User u) { Session s=null; try { s=sessionFactory.getCurrentSession(); s.beginTransaction(); s.save(u); s.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); s.getTransaction().rollback(); }finally{ if(s!=null){ s.close(); s=null; } } System.out.println("add success!!"); }
package cn.edu.hpu.HibernateTemplate; import org.hibernate.Session; public class MyHibernateTemplate { public void executeWithNativeSession(MyHibernateCallback callback){ Session s=null; try { s=getSession(); s.beginTransaction(); callback.doInHibernate(s);//这里的方法用户自己就可以在接口里去写(save什么的) s.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); s.getTransaction().rollback(); }finally{ if(s!=null){ s.close(); s=null; } } } public Session getSession(){ //拿Session,这里就省略不写了 Session session=null; return session; } }
package cn.edu.hpu.HibernateTemplate; import org.hibernate.Session; public interface MyHibernateCallback { public void doInHibernate(Session s); } //如何去用MyHibernateTemplate方法 public static void main(String[] args) { new MyHibernateTemplate().executeWithNativeSession(new MyHibernateCallback() { public void doInHibernate(Session s) { s.save(null);//或其他事务 } }); }是不是更加理解HibernateTemplate了?
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <context:annotation-config/> <context:component-scan base-package="cn.edu.hpu"/> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:com/foo/jdbc.properties</value> </property> </bean> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="annotatedClasses"> <list> <value>cn.edu.hpu.model.User</value> <value>cn.edu.hpu.model.Log</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <!-- 有关事务的配置 --> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <!-- tx的Annotation配置 --> <!-- <tx:annotation-driven transaction-manager="txManager"/> --> <aop:config> <aop:pointcut expression="execution(public * cn.edu.hpu.service..*.*(..))" id="businessService"/> <aop:advisor pointcut-ref="businessService" advice-ref="txAdvice"/> </aop:config> <tx:advice id="txAdvice" transaction-manager="txManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="add*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <!--hibernateTemplate的配置--> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans>
package cn.edu.hpu.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class User { private int id; private String name; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package cn.edu.hpu.dao; import org.springframework.stereotype.Component; import cn.edu.hpu.model.User; public interface UserDao { public void save(User u); }
package cn.edu.hpu.dao.Impl; import javax.annotation.Resource; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.stereotype.Component; import cn.edu.hpu.dao.UserDao; import cn.edu.hpu.model.User; @Component("u") public class UserDaoImpl implements UserDao{ private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } @Resource(name="hibernateTemplate") public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } public void save(User u) { hibernateTemplate.save(u); System.out.println("add success!!"); } }
package cn.edu.hpu.service; import javax.annotation.Resource; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import cn.edu.hpu.dao.LogDao; import cn.edu.hpu.dao.UserDao; import cn.edu.hpu.model.Log; import cn.edu.hpu.model.User; @Component("userService") public class UserService { private UserDao userDao; public UserDao getUserDao() { return userDao; } @Resource(name="u") public void setUserDao(UserDao userDao) { this.userDao = userDao; } public void add(User u){ this.userDao.save(u); } }
package cn.edu.hpu.service; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.edu.hpu.model.User; public class UserServiceTest { @Test public void testAdd() throws Exception{ ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml"); UserService userService=(UserService)ctx.getBean("userService"); System.out.println(userService.getClass()); User u=new User(); u.setName("jack"); userService.add(u); ctx.destroy(); } }
package cn.edu.hpu.dao.Impl; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import org.springframework.stereotype.Component; import cn.edu.hpu.dao.LogDao; import cn.edu.hpu.model.Log; @Component("logDao") public class LogDaoImpl extends HibernateDaoSupport implements LogDao{ public void save(Log log) { this.getHibernateTemplate().save(log); //或直接this.save(log); System.out.println("Log add success!!"); } }
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <context:annotation-config/> <context:component-scan base-package="cn.edu.hpu"/> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:com/foo/jdbc.properties</value> </property> </bean> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="annotatedClasses"> <list> <value>cn.edu.hpu.model.User</value> <value>cn.edu.hpu.model.Log</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> <bean id="logDao" class="cn.edu.hpu.dao.Impl.LogDaoImpl"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> </beans>
package cn.edu.hpu.service; import org.junit.Test; import org.springframework.context.support.ClassPathXmlApplicationContext; import cn.edu.hpu.model.Log; public class UserServiceTest { @Test public void testAdd() throws Exception{ ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml"); UserService userService=(UserService)ctx.getBean("userService"); System.out.println(userService.getClass()); Log log=new Log(); userService.add(log); ctx.destroy(); } }测试结果:
能不用继承就不用继承,HibernateDaoSupport的使用不太重要,尽量使用方法一吧。
转载请注明出处:http://blog.csdn.net/acmman/article/details/44652207