package com.hust.dong;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
public class App {
private static SessionFactory sessionFactory;
static {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml"); // 读取指定的主配置文件
sessionFactory = cfg.buildSessionFactory(); // 根据配置生成Session工厂
}
@Test
public void testSave() {
User user = new User();
user.setName("zhangsan");
// 保存
Session session = sessionFactory.openSession(); // 打开一个新的Session
Transaction tx = session.beginTransaction(); // 开启事务
session.save(user);
tx.commit(); // 提交事务
session.close(); // 关闭Session,释放资源(不一定是真正的关闭)
}
@Test
public void testGet() {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = (User) session.get(User.class, 4); //
System.out.println(user);
tx.commit();
session.close();
}
}
创建数据库
mysql -u root -p
create database cm_hibernate default character set utf8;
use cm_hibernate;
create table t_user( id int primary key auto_increment, name varchar(20) );
运行即可
http://blog.csdn.net/yerenyuan_pku/article/details/52733275