hibernate在写数据库配置文件时非常的不确定,必须进行必要的测试保证数据库结构的正确性。所以可以应用junit进行测试。
使用junit非常简单,eclipse只需要右键项目新建一个junit test case即可(填写类名和包名)。然后在对应位置写对应的代码运行测试即可。
下面给出一个常用的hibernate测试框架:
package com.atguigu.hibernate.entities;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Date;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.jdbc.Work;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class HibernateTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Before
public void init(){
Configuration configuration = new Configuration().configure();
ServiceRegistry serviceRegistry =
new ServiceRegistryBuilder().applySettings(configuration.getProperties())
.buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
@After
public void destroy(){
transaction.commit();
session.close();
sessionFactory.close();
}
@Test
public void testComponent(){
Worker worker = new Worker();
Pay pay = new Pay();
pay.setMonthlyPay(1000);
pay.setYearPay(80000);
pay.setVocationWithPay(5);
worker.setName("ABCD");
worker.setPay(pay);
session.save(worker);
}
@Test
public void testBlob() throws Exception{
// News news = new News();
// news.setAuthor("cc");
// news.setContent("CONTENT");
// news.setDate(new Date());
// news.setDesc("DESC");
// news.setTitle("CC");
//
// InputStream stream = new FileInputStream("Hydrangeas.jpg");
// Blob image = Hibernate.getLobCreator(session)
// .createBlob(stream, stream.available());
// news.setImage(image);
//
// session.save(news);
News news = (News) session.get(News.class, 1);
Blob image = news.getImage();
InputStream in = image.getBinaryStream();
System.out.println(in.available());
}
@Test
public void testPropertyUpdate(){
News news = (News) session.get(News.class, 1);
news.setTitle("aaaa");
System.out.println(news.getDesc());
System.out.println(news.getDate().getClass());
}
@Test
public void testIdGenerator() throws InterruptedException{
News news = new News("AA", "aa", new java.sql.Date(new Date().getTime()));
session.save(news);
// Threa