日期:2014-05-16 浏览次数:20512 次
package org.ourpioneer.course.bean; import java.sql.Date; /** * 课程信息描述bean * * @author Nanlei * */ public class Course { private Long id; private String title; private java.util.Date startDate; private java.util.Date endDate; private int fee; //必须提供无参默认构造方法 public Course() { super(); } //省略其它构造方法,getter和setter等方法 }
package org.ourpioneer.course.dao; import java.util.List; import org.ourpioneer.course.bean.Course; public interface CourseDAO { public void save(Course course); public void delete(Course course); public void update(Course course); public Course findById(Long courseId); public List<Course> findAll(); }
package org.ourpioneer.course.dao; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.ourpioneer.course.bean.Course; public class CourseDAOImpl implements CourseDAO { private SessionFactory sessionFactory; public CourseDAOImpl() { Configuration cfg = new Configuration().configure(); sessionFactory = cfg.buildSessionFactory(); } public List<Course> findAll() { Session session = sessionFactory.openSession(); try { Query query = session.createQuery("from Course"); return query.list(); } finally { session.close(); } } public Course findById(Long courseId) { Session session = sessionFactory.openSession(); try { return (Course) session.get(Course.class, courseId); } finally { session.close(); } } public void save(Course course) { Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); try { tx.begin(); session.saveOrUpdate(course); tx.commit(); } catch (RuntimeException e) { tx.rollback(); throw e; } finally { session.close(); } } }
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql:///test</property> <property name="connection.username">root</property> <property name="connection.password">123</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <mapping resource="org/ourpioneer/course/hbm/course.hbm.xml" /> </session-factory> </hibernate-configuration>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate