Hibernate使用JUnit进行测试
程序员文章站
2022-04-16 14:28:28
...
一 Junit常用注解
@Test:测试方法
@Before:初始化方法
@After:释放资源
二 创建测试类StudentsTest
三 通过Hibernate API编写访问数据库的代码骨架
四 测试代码
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; //测试类 public class StudentsTest { private SessionFactory sessionFactory; private Session session; private Transaction transaction; @Before public void init(){ // 创建配置对象 Configuration config = new Configuration().configure(); //config.addClass(Students.class); // 创建服务注册对象 ServiceRegistry serviceRegistery = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry(); // 创建会话工厂对象 sessionFactory = config.buildSessionFactory(serviceRegistery); // 创建会话对象 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,"张三丰","男",new Date(),"武当山"); session.save(s); } }
五 测试输出
Hibernate:
drop table if exists STUDENTS
Hibernate:
create table STUDENTS (
SID integer not null,
SNAME varchar(255),
GENDER varchar(255),
BIRTHDAY datetime,
ADDRESS varchar(255),
primary key (SID)
)
九月 17, 2017 3:31:29 下午 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Hibernate:
insert
into
STUDENTS
(SNAME, GENDER, BIRTHDAY, ADDRESS, SID)
values
(?, ?, ?, ?, ?)
六 测试结果