完整的学习项目放在了我的github上,是一个半成品的在线音乐网站。
hibernate版本1.4 下面是userDAO 即对user表进行增删改查
1 public class UserDAO { 2 public static void insertUser(User user) { 3 Transaction tx = null; 4 try { 5 Session session = HibernateSessionFactory.getSessionFactory() 6 .openSession(); 7 tx = session.beginTransaction(); 8 session.save(user); 9 tx.commit();10 } catch (HibernateException e) {11 e.printStackTrace();12 tx.rollback();13 }14 HibernateSessionFactory.closeSession();15 }//add16 17 18 public static void deleteUser(String userId) {19 Transaction tx = null;20 try {21 User user = getUser(userId);22 Session session = HibernateSessionFactory.getSessionFactory()23 .openSession();24 tx = session.beginTransaction();25 session.delete(user);26 tx.commit();27 } catch (Exception e) {28 e.printStackTrace();29 tx.rollback();30 }31 HibernateSessionFactory.closeSession();32 }//delete33 34 35 public static void updateUser(User user) {36 Transaction tx = null;37 try {38 Session session = HibernateSessionFactory.getSessionFactory()39 .openSession();40 tx = session.beginTransaction();41 session.update(user);42 tx.commit();43 } catch (Exception e) {44 e.printStackTrace();45 tx.rollback();46 }47 HibernateSessionFactory.closeSession();48 }//update49 50 51 public static User getUser(String userId) {52 Transaction tx = null;53 User user = null;54 try {55 Session session = HibernateSessionFactory.getSessionFactory()56 .openSession();57 tx = session.beginTransaction();58 user = (User) session.get(User.class, userId);59 tx.commit();60 } catch (HibernateException e) {61 e.printStackTrace();62 tx.rollback();63 }64 HibernateSessionFactory.closeSession();65 return user;66 }//get one67 68 69 public static List getUsers() {70 Transaction tx = null;71 List list = null;72 try {73 Session session = HibernateSessionFactory.getSessionFactory()74 .openSession();75 tx = session.beginTransaction();76 Query query = session.createQuery("from User order by userId desc");77 list = query.list();78 tx.commit();79 } catch (Exception e) {80 e.printStackTrace();81 tx.rollback();82 }83 HibernateSessionFactory.closeSession();84 return list;85 }// get all
原标题:hibernateDAO层基本的增删改查
关键词:Hibernate