Hibernate系列之----session保存对象


测试一

public void testSave1(){
		Session session = null;
		Transaction tx = null;
		try{
			session = HibernateUtils.getSession();
			tx = session.beginTransaction();
			
			User user = new User();
			user.setName("李四");
			user.setPassword("123");
			user.setCreateTime(new Date());
			user.setExpireTime(new Date());
			
			session.save(user);
			
			tx.commit();
		}catch (Exception e) {
			tx.rollback();
		}finally{
			HibernateUtils.closeSession(session);
		}
	}

执行:

Hibernate: insert into User (name, password, createTime, expireTime, id) values (?, ?, ?, ?, ?)


测试二

public void testSave1(){
Session session = null;
Transaction tx = null;
try{
session = HibernateUtils.getSession();
tx = session.beginTransaction();

User user = new User();
user.setName("李四");
user.setPassword("123");
user.setCreateTime(new Date());
user.setExpireTime(new Date());

session.save(user);

user.setName("王五");

tx.commit();
}catch (Exception e) {
tx.rollback();
}finally{
HibernateUtils.closeSession(session);
}
}


执行:

Hibernate: insert into User (name, password, createTime, expireTime, id) values (?, ?, ?, ?, ?)
Hibernate: update User set name=?, password=?, createTime=?, expireTime=? where id=?


测试三

public void testSave1(){
Session session = null;
Transaction tx = null;
User user = null;

try{
session = HibernateUtils.getSession();
tx = session.beginTransaction();

user = new User();
user.setName("李四");
user.setPassword("123");
user.setCreateTime(new Date());
user.setExpireTime(new Date());

session.save(user);

user.setName("王五");

tx.commit();
}catch (Exception e) {
tx.rollback();
}finally{
HibernateUtils.closeSession(session);
}


user.setName("张三");
try{
session = HibernateUtils.getSession();
tx = session.beginTransaction();

session.update(user);
tx.commit();
}catch (Exception e) {
tx.rollback();
}finally{
HibernateUtils.closeSession(session);
}


}


执行:

Hibernate: insert into User (name, password, createTime, expireTime, id) values (?, ?, ?, ?, ?)
Hibernate: update User set name=?, password=?, createTime=?, expireTime=? where id=?
Hibernate: update User set name=?, password=?, createTime=?, expireTime=? where id=?







你可能感兴趣的:(Date,Hibernate,exception,session,user,insert)