测试代码:
package com.hb3.pack_01;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.hb3.pack_01.model.User;
public class BusinessService {
public static void main(String[] args) {
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.openSession();
//insert
User user = new User();
user.setName("chenyan");
//user.setAge(new Integer(23));
Transaction tx = session.beginTransaction();
session.save(user);
tx.commit();
//get
user = (User) session.get(User.class, user.getId());
System.out.println(user.getAge());
//update
user.setAge(new Integer(24));
tx= session.beginTransaction();
session.update(user);
tx.commit();
//load
user = (User) session.load(User.class, user.getId());
System.out.println(user.getAge());
//delete
tx = session.beginTransaction();
session.delete(user);
tx.commit();
session.close();
sessionFactory.close();
}
}
执行结果:
11:50:50,750 WARN ConfigurationFactory:127 - No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/D:/Java/MyEclipse%206.0/workspace/hb3demo/ehcache-1.2.3.jar!/ehcache-failsafe.xml
11:50:51,156 WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.UpdateTimestampsCache]; using defaults.
11:50:51,171 WARN EhCacheProvider:93 - Could not find configuration [org.hibernate.cache.StandardQueryCache]; using defaults.
Hibernate: insert into user (name, age) values (?, ?)
null
Hibernate: update user set name=?, age=? where id=?
24