package org.Rudiment.hibernate;
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
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;
public class HibernateHandler {
/* 插入新数据 */
public static void InsertObejct(News n)
{
//创建一个配置对象
Configuration conf = new Configuration();
ServiceRegistry sr = new ServiceRegistryBuilder()
.applySettings(conf.getProperties())
.buildServiceRegistry();
//通过配置对象获得 SessionFactory
SessionFactory sf = conf.configure().buildSessionFactory(sr);
//通过 SessionFactory 获取到一个 Session
Session sess = sf.openSession();
//开始Session事务的会话
Transaction tx = sess.beginTransaction();
//设置这个实例的 title
n.setTitle("hibernate框架1");
//设置这个实例的 content
n.setContent("hibernate框架插入的内容2");
//保存实例
sess.save(n);
//提交事务
tx.commit();
//关闭会话
sess.close();
//关闭会话工厂
sf.close();
}
/* 查询记录 */
public News queryById(int id)
{
Configuration conf = new Configuration();
ServiceRegistry sr = new ServiceRegistryBuilder()
.applySettings(conf.getProperties())
.buildServiceRegistry();
SessionFactory sf = conf.configure().buildSessionFactory(sr);
Session sess = sf.openSession();
String hql = "from News as n where n.id=?";
Query query = sess.createQuery(hql);
query.setInteger(0, id);
List rsList = query.list();
Iterator it=rsList.iterator();
News news = null;
while(it.hasNext())
{
news = (News)it.next();
}
sess.close();
return news;
}
/* 更新记录 */
public News updateById(int id)
{
News n = queryById(id);
Configuration conf = new Configuration();
ServiceRegistry sr = new ServiceRegistryBuilder()
.applySettings(conf.getProperties())
.buildServiceRegistry();
SessionFactory sf = conf.configure().buildSessionFactory(sr);
Session sess = sf.openSession();
Transaction t = sess.beginTransaction();
n.setTitle("修改了,我是" + id);
n.setContent("内容也改了" + id + "!");
sess.update(n);
t.commit();
sess.close();
return queryById(id);
}
/* 删除记录 */
public boolean deleteById(int id)
{
Configuration conf = new Configuration();
ServiceRegistry sr = new ServiceRegistryBuilder()
.applySettings(conf.getProperties())
.buildServiceRegistry();
SessionFactory sf = conf.configure().buildSessionFactory(sr);
Session sess = sf.openSession();
String hql = "delete News as n where n=?";
Query query = sess.createQuery(hql);
query.setInteger(0, id);
query.executeUpdate();
sess.beginTransaction().commit();
return true;
}
public static void main(String[] args)
{
long p_t = System.currentTimeMillis();
for(int i=0; i<10; i++)
{
News n = new News();
HibernateHandler.InsertObejct(n);
}
long l_t = System.currentTimeMillis();
long useTime = (l_t - p_t)/ 1000;
System.out.println("耗时: " + (useTime) + " 秒钟");
}
}
|