- hibernate 业务流程
1 创建配置对象 Configuration config = new Configuration().configure();
2 创建服务注册对象 ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applysettings(config.getProperties()).buildServiceRegistry();
3 创建会话工厂 SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry);
4 开启会话 Session session = sessionFactory.openSession();
5 开启事务 Transaction transaction = session.beginTransaction();
6 写业务逻辑
7 提交事务 transaction.commit();
8 关闭会话 session.close();
9 关闭会话工厂 sessionFactory.close();
- hibernate 实现功能:
1 生成数据对象
2 数据库创建表结构
3 数据库插入表数据
- 代码:
package hibernate_001;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.ddwei.student.Student;
public class StudentTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction trasaction;
@Test
public void testSaveStudent(){
Student student =new Student(1,"周恩来","男",new Date(),"绍兴");//创建学生对象
session.save(student);//会话保存学生对象进入数据库
}
@Before
public void init(){
//1 创建配置对象
Configuration config = new Configuration().configure();
//2 创建服务对象
ServiceRegistry serviceRe = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//3 创建会话工厂
sessionFactory = config.buildSessionFactory(serviceRe);
//4 打开会话
session = sessionFactory.openSession();
//5 创建事务
trasaction = session.beginTransaction();
}
@After
public void destroy(){
trasaction.commit();
session.close();
sessionFactory.close();
}
}