public interface userDao {
//增加
public void add(user us);
//查询
public void find(user us);
//删除
public void delete(String tno);
//修改
public void update(user us);
}
————————————————
public class userDaoImpl implements userDao{
public void add(user us) {
// TODO 自动生成的方法存根
SessionFactory sf = null;
Session session = null;
Transaction ts = null;
System.out.println("1");
try {
sf = HibernateUtil.getSessionFactory();
session = sf.getCurrentSession();
ts = session.beginTransaction();
session.save(us);
System.out.println(us.toString());
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
if(ts != null)
{
ts.rollback();
}
e.printStackTrace();
}
}
@Override
public void delete(String tno) {
// TODO 自动生成的方法存根
SessionFactory sf = null;
Session session = null;
Transaction ts = null;
try {
sf = HibernateUtil.getSessionFactory();
session = sf.getCurrentSession();
ts = session.beginTransaction();
user p = (user) session.get(user.class, tno);
session.delete(p);
System.out.println(p.getTno());
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
if(ts != null)
{
ts.rollback();
}
e.printStackTrace();
}
}
@Override
public void update(user us) {
// TODO 自动生成的方法存根
SessionFactory sf = null;
Session session = null;
Transaction ts = null;
try {
sf = HibernateUtil.getSessionFactory();
session = sf.getCurrentSession();
ts = session.beginTransaction();
session.update(us);
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
if(ts != null)
{
ts.rollback();
}
e.printStackTrace();
}
}
@Override
public void find(user us) {
// TODO 自动生成的方法存根
SessionFactory sf = null;
Session session = null;
Transaction ts = null;
//user us1 = new user();
try {
sf = HibernateUtil.getSessionFactory();
session = sf.getCurrentSession();
ts = session.beginTransaction();
Criteria criteria =session.createCriteria(user.class);
List<user> list = criteria.list();
//使用forEach遍历集合
for (user user : list) {
System.out.println(user);
}
ts.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
if(ts != null)
{
ts.rollback();
}
e.printStackTrace();
}
}
}
public class userTest {
userDaoImpl uImpl = new userDaoImpl();
@Test
public void testadd(){
user us = new user("1","张三","40","女","讲师");
uImpl.add(us);
}
@Test
public void testfind() {
user user=new user();
uImpl.find(user);
}
@Test
public void testdelete() {
uImpl.delete("5");
}
@Test
public void testupdate() {
user us=new user("2", "老王","50", "男","学生");
uImpl.update(us);
}
}