日期:2014-05-16 浏览次数:20365 次
package org.ourpioneer.course.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.ourpioneer.course.bean.Course; import org.springframework.transaction.annotation.Transactional; public class CourseDAOImplHibernate implements CourseDAO { private SessionFactory sessionFactory; public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Transactional public void delete(Course course) { sessionFactory.getCurrentSession().delete(course); } @Transactional(readOnly = true) public List<Course> findAll() { Query query = sessionFactory.getCurrentSession().createQuery( "from Course"); return query.list(); } @Transactional(readOnly = true) public Course findById(Long courseId) { return (Course) sessionFactory.getCurrentSession().get(Course.class, courseId); } @Transactional public void save(Course course) { sessionFactory.getCurrentSession().saveOrUpdate(course); } @Transactional public void update(Course course) { sessionFactory.getCurrentSession().update(course); } }
<tx:annotation-driven /> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <bean id="courseDaoHibernate" class="org.ourpioneer.course.dao.CourseDAOImplHibernate"> <property name="sessionFactory" ref="sessionFactory" /> </bean>
package org.ourpioneer.course; import java.util.GregorianCalendar; import java.util.List; import org.ourpioneer.course.bean.Course; import org.ourpioneer.course.dao.CourseDAO; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Demo { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "classpath:applicationContext.xml"); CourseDAO courseDAO = (CourseDAO) ctx.getBean("courseDaoHibernate"); Course course = new Course(); course.setTitle("Spring ORM"); course.setStartDate(new GregorianCalendar(2011, 2, 1).getTime()); course.setEndDate(new GregorianCalendar(2011, 3, 1).getTime()); course.setFee(100); courseDAO.save(course); List<Course> courses = courseDAO.findAll(); Long courseId = courses.get(0).getId(); course = courseDAO.findById(courseId); System.out.println(course); course.setFee(200); courseDAO.update(course); System.out.println(course); courseDAO.delete(course); } }
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"></bean>
package org.ourpioneer.course.dao; import java.util.List; import javax.