JavaProject 中一个试验插入的main() 中
public static void main()[Stirng [] args]{
//第一步就是先读取配置文件
Configuration conf = new Configuration().configure();
//HIbernate的操作要使用Session来完成, 而Session是由SessionFactory来管理, 那么就生成SessionFactory
SessionFactory sf = conf.buildSessionFactory();
Transaction tx = null ;
try {
//打开session,并开始事务
Session session = sf.openSession();
tx = session.beginTransaction();
TCustomer c = new TCustomer("111","yuyang",9000D);
session.save(c);
tx.commit();
} catch (HibernateException e) {
// TODO Auto-generated catch block
if(tx != null){
tx.rollback();
}
e.printStackTrace();
}
}
想 更新 删除 操作是必须要有Transaction 的 ,而且需要先查询出对象, 再做修改 再更新或者删除
public static void main(String[] args) {
// TODO Auto-generated method stub
Configuration conf = new Configuration().configure();
SessionFactory sf = conf.buildSessionFactory();
Transaction tx = null ;
Session session = sf.openSession();
TCustomer c = new TCustomer();
session.load(c, 101);
c.setCustomerbalance(c.getCustomerbalance()+189);
session.update(c);
System.out.println(c.getCustomername());
System.out.println(c.getPassword());
System.out.println(c.getCustomerbalance());
}
而像查询这种方法是不需要 Transaction的