hibernate保存操作 记得开启事务
public void test1(){
Session session = HibernateUtil.openSession();
//获取session
Transaction transaction = session.beginTransaction();
Customer customer = new Customer();
customer.setCust_name("LeBron");
customer.setCust_level("1");
//保存
session.save(customer);
transaction.commit();
//释放资源
session.close();
}
hibernate获取一条记录(根据id获取一条记录 )
session.get(类名.class,id) 因为id是long类型,所以要加上L
public void test2(){
Session session = HibernateUtil.openSession();
Customer customer = session.get(Customer.class, 1L);
System.out.println(customer);
session.close();
}
更新操作 记得开启事务
1.直接new一个新对象,设置其id,再设置其他字段属性。然后session.update(customer)
这样做的问题是没有设置的字段属性将默认为null 不推荐
public void test3(){
Session session = HibernateUtil.openSession();
Transaction transaction = session.beginTransaction();
Customer customer = new Customer();
customer.setCust_id(2L);
customer.setCust_name("wade");
session.update(customer);
transaction.commit();
session.close();
}
2.先查询,得到一个对象,设置字段属性后,再更新 推荐使用
public void test3(){
Session session = HibernateUtil.openSession();
Transaction transaction = session.beginTransaction();
Customer customer = session.get(Customer.class, 3L);
customer.setCust_name("Anthony");
session.update(customer);
transaction.commit();
session.close();
}
删除操作 记得开启事务
1.直接创建对象删除 不支持级联删除
2.先查再删 支持级联删除
public void test4(){
Session session = HibernateUtil.openSession();
Transaction transaction = session.beginTransaction();
Customer customer = session.get(Customer.class, 4L);
session.delete(customer);
transaction.commit();
session.close();
}
保存或更新 记得开启事务
如果给对象没有设置id 就是保存操作
如果设置了id 就是更新操作 如果设置的id不存在 则报错
public void test5(){
Session session = HibernateUtil.openSession();
Transaction transaction = session.beginTransaction();
Customer customer = new Customer();
//如果没有设置ID是保存操作
customer.setCust_name("paul");
customer.setCust_level("3");
session.saveOrUpdate(customer);
transaction.commit();
session.close();
}
public void test5(){
Session session = HibernateUtil.openSession();
Transaction transaction = session.beginTransaction();
Customer customer = new Customer();
//如果没有设置ID是保存操作
customer.setCust_id(1L);
customer.setCust_name("LeBron");
customer.setCust_level("23");
session.saveOrUpdate(customer);
transaction.commit();
session.close();
}
查询所有
使用hibernate内置的HQL 是纯面向对象的操作 查询的是类名
public void test6(){
Session session = HibernateUtil.openSession();
Transaction transaction = session.beginTransaction();
//查询所有HQL 查询的是类名
Query query = session.createQuery("from com.bullet.domain.Customer ");
List list = query.list();
for (Object o : list) {
System.out.println(o);
}
transaction.commit();
session.close();
}