import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import cn.itcast.cc.hibernate.persistence.Customer; public class Main { private static SessionFactory sefac = null; // 当类被加载时,获取SessionFactory。 static { //创建Configuration时,默认加载hibernate.properties文件。 //也可以调用addResource方法,将配置文件加载进来。 Configuration config = new Configuration(); // 将ORM中的O在此添加到 config.addClass(Customer.class); sefac = config.buildSessionFactory(); } public static void main(String[] args) { // 创建一个customer对象 Customer customer = new Customer(); customer.setName("changcheng"); customer.setGender(1); customer.setBirthday(new Date()); customer.setPhone("13998689955"); customer.setEmail("changcheng@google.com"); customer.setAddress("China"); // 调用保存 save(customer); // 调用查询 find(1); } private static void save(Customer customer){ //获取session相当于获取了一个连接 Session session = sefac.openSession(); //此处必须使用事务,否则不能保存数据。 Transaction tr = session.beginTransaction(); //直接保存 session.save(customer); //提交事务 tr.commit(); //关闭会话 session.close(); } private static void find(Integer id){ //获取session相当于获取了一个连接 Session session = sefac.openSession(); Transaction tra = session.beginTransaction(); //直接保存 Customer customer = (Customer) session.load(Customer.class, id); tra.commit(); //关闭会话 session.close(); System.out.println(customer); } } |