首页 > IT职业 > IT生活 > 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.*;
public class StudentsTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Before
public void init(){
//创建配置对象
Configuration config =new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry =new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
//创建会化工厂
sessionFactory = config.buildSessionFactory(serviceRegistry);
//绘画对象
session = sessionFactory.openSession();
//开启事务
transaction = session.beginTransaction();
}
@After
public void destory(){
transaction.commit();
session.close();
sessionFactory.close();
}
@Test
public void testSaveStudents(){
//生成学生对象
Students s =new Students(1,"pp","男", new Date(),"11A403");
session.save(s);//保存对象进入数据库
}
}
`
hibernate.cfg.xml
'
br/> "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
org.hibernate.dialect.MySQLDialect
jdbc:mysql:///hibernate?useUnicode=true&characterEncoding=UTF-8
root
com.mysql.jdbc.Driver
com.mysql.jdbc.Driver
true true <!-- hibernate数据表表前缀 -->hibernate <!-- 创建数据库生成策略 create 表示重新生成表结构 update保留原有的表结构-->create thread <!-- jta事务 全局事务
jta
-->
'
'
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/835/viewspace-2807766/ ,如需转载,请注明出处,否则将追究法律责任。