基于Hibernate实现CRUD
增加
public void testSave(){
Customer c=new Customer();
c.setName("a");
Configuration cfg=new Configuration().configure();
SessionFactory factory=cfg.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
session.save(c);
tx.commit();
session.close();
factory.close();
}
结果:
删除
public void testDel(){
Configuration cfg=new Configuration().configure();
SessionFactory factory=cfg.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
Customer c=(Customer) session.get(Customer.class,1);
session.delete(c);
tx.commit();
session.close();
factory.close();
}
结果:
修改
public void testUpdate(){
Configuration cfg=new Configuration().configure();
SessionFactory factory=cfg.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
Customer c=(Customer) session.get(Customer.class,1);
c.setName("b");
session.update(c);
System.out.println(c);
tx.commit();
session.close();
factory.close();
}
查询
public void testFindOne(){
Configuration cfg=new Configuration().configure();
SessionFactory factory=cfg.buildSessionFactory();
Session session=factory.openSession();
Transaction tx=session.beginTransaction();
Customer c=(Customer) session.get(Customer.class,1);
System.out.println(c);
tx.commit();
session.close();
factory.close();
}