DAO接口
public interface UserDao {
public User findById(int id);
public boolean add(User user);
public boolean update(User user);
public boolean delete(int user);
}
DAO实现类
package DAO;
import core.HibernateUtil;
import entity.User;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
public class UserDaoImpl implements UserDao{
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
public boolean add(User user) {
Transaction tx = null;
Session session = sessionFactory.openSession();
try {
tx = session.beginTransaction();// 4、开始一个事务
session.save(user);
tx.commit();// 6、 提交事务
} catch (Exception e) {
e.printStackTrace();
if(tx != null)
tx.rollback();
return false;
} finally {
session.close();
}
return true;
}
public boolean delete(int id) {
Transaction tx = null;
Session session = sessionFactory.openSession();
try {
tx = session.beginTransaction();
User user = session.get(User.class, id);
session.delete(user);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
if(tx != null)
tx.rollback();
return false;
} finally {
session.close();
}
return true;
}
public boolean update(User user) {
Transaction tx = null;
Session session = sessionFactory.openSession();
try {
tx = session.beginTransaction();
session.update(user);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
if(tx != null)
tx.rollback();
return false;
} finally {
session.close();
}
return true;
}
public User findById(int id) {
Session session = sessionFactory.openSession();
Transaction tx = null;
User user = null;
try {
tx = session.beginTransaction();
user = session.get(User.class, id);
tx.commit();
} catch (Exception e) {
e.printStackTrace();
if(tx != null)
tx.rollback();
return null;
} finally {
session.close();
}
return user;
}
}