hibernate.cfg.xml配置(Oracle+c3p0)
说明:数据库:Oracle10g;连接池:c3p0
结构:
一、配置hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- c3p0连接池 -->
<hibernate-configuration>
<session-factory>
<!-- 显示实际操作数据库时的SQL -->
<property name="show_sql">true</property>
<!-- SQL方言,这边设定的是Oracle -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!--驱动程序:Oracle数据库的配置 -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<!-- JDBC URL -->
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:myorcl</property>
<!-- 数据库用户名 -->
<property name="connection.username">scott</property>
<!-- 数据库密码 -->
<property name="connection.password">root</property>
<!-- 指定连接池里最小连接数 -->
<property name="hibernate.cp30.minsize">5</property>
<!-- 指定连接池里的最大连接数 -->
<property name="hibernate.c3p0.maxsize">20</property>
<!-- 指定连接池里的超时时常 -->
<property name="hibernate.cp30.timeout">1800</property>
<!-- 指定连接池里最大缓存多少个Statement对象 -->
<property name="hibernate.cp30.max_statements">50</property>
<!-- 根据需要自动创建数据库表 -->
<property name="hbm2ddl.auto">update</property>
<!-- 对象与数据库表格映像文件 -->
<mapping resource="com/chen/vo/News.hbm.xml"/>
</session-factory>
</hibernate-configuration>
二、配置News.hbm.xml
说明:由于连接的数据库是Oracle,所有这里指定了序列:seq_news,如果设置<generator class="native"/>,则在插入数据时Hibernate默认会去查找Oracle中的hibernate_sequence序列(默认序列)。
<?xml version="1.0" encoding="utf-8"?>
<!-- 指定Hibernate映射文件的DTD信息 -->
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- hibernate-mapping是映射文件的根源素 -->
<hibernate-mapping>
<!-- 每个class对应一个持久化对象 -->
<class name="com.chen.vo.News" table="news_table">
<!-- id元素定义持久化类的标识属性 -->
<id name="id">
<generator class="sequence">
<param name="sequence">seq_news</param>
</generator>
</id>
<!-- property元素定义常规属性 -->
<property name="title"/>
<property name="content"/>
</class>
</hibernate-mapping>
三、创建vo
package com.chen.vo;
public class News
{
//消息类的标识属性
private Integer id;
//消息标题
private String title;
//消息内容
private String content;
//id属性的setter和getter方法
public void setId(Integer id)
{
this.id=id;
}
public Integer getId()
{
return this.id;
}
//title属性的setter和getter方法
public void setTitle(String title)
{
this.title=title;
}
public String getTitle()
{
return this.title;
}
//content 属性的setter和getter方法
public void setContent(String content)
{
this.content=content;
}
public String getContent()
{
return this.content;
}
}
四、创建测试类
package com.chen.vo;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class NewsManager {
public static void main(String[] args) throws Exception
{
//实例化configuration
Configuration conf =new Configuration().configure();
//以Configuration创建SessionFactory.注:buildSessionFactory方法已过时,不过仍可以获取SessionFactory。
// SessionFactory sf=conf.buildSessionFactory();
//采用ServiceRegistry获取SessionFactory
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
ServiceRegistry serviceRegistry = serviceRegistryBuilder.applySettings(conf.getProperties()).build();
SessionFactory sf = conf.buildSessionFactory(serviceRegistry);
//创建session
Session sess = sf.openSession();
//开始事物
Transaction tx = sess.beginTransaction();
//创建消息实例
News n=new News();
//设置消息标题和消息内容
/**
* Oracle插入数据说明:
* 1.在News.hbm.xml中设置<generator class="native"/>
* 连接Oracle,默认序列(Default.sequence)为hibernate_sequence
* 使用native时Hibernate默认会去查找Oracle中的hibernate_sequence序列,所以插入数据时无需设置id。
* 2.在News.hbm.xml中设置指定序列:
* <generator class="sequence">
<param name="sequence">seq_news</param>
</generator>
* Hibernate会按照序列seq_news创建新数据。
*/
n.setTitle("title2");
n.setContent("content2");
//保存消息
sess.save(n);
//提交事务
tx.commit();
//关闭Session
sess.close();
sf.close();
}
}
测试结果:
五、创建junit测试类、HibernateSessionFactory,通过session实现增、删、查、改
1.创建HibernateSessionFactory
package com.chen.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateSessionFactory {
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
//private static String configfile = "/hibernate.cfg.xml";
private static Configuration configuration = new Configuration().configure();
private static SessionFactory sessionFactory;
static {
try {
StandardServiceRegistryBuilder serviceRegistryBuilder = new StandardServiceRegistryBuilder();
ServiceRegistry serviceRegistry = serviceRegistryBuilder.applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (HibernateException e) {
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
public static Session getSession() {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
public static void closeSesssion() {
Session session = threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setSessionFactory(SessionFactory sessionFactory) {
HibernateSessionFactory.sessionFactory = sessionFactory;
}
public static Configuration getConfiguration() {
return configuration;
}
public static void setConfiguration(Configuration configuration) {
HibernateSessionFactory.configuration = configuration;
}
}
2.在测试类进行测试
package com.chen.test;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;
import com.chen.utils.HibernateSessionFactory;
import com.chen.vo.News;
public class HibernateTest {
//获取session
@Test
public void sessionTest(){
Session session = HibernateSessionFactory.getSession();
System.out.println(session);
}
//查询News的列表信息
@Test
public void listNews(){
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery("from News");
List<?> list = query.list();
System.out.println(list);
}
//通过id查询指定的News
@Test
public void findById(){
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery("from News where id=?");
//设置参数
query.setParameter(0, 1);
//单值检索
News n = (News) query.uniqueResult();
System.out.println(n);
}
//添加News
@Test
public void saveNews(){
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
News n=new News();
n.setTitle("title3");
n.setContent("content3");
session.saveOrUpdate(n);;
tx.commit();
session.close();
}
//修改News
@Test
public void updateNews(){
Session session = HibernateSessionFactory.getSession();
//先获取指定id的News
Query query = session.createQuery("from News where id=?");
query.setParameter(0, 5);
News n = (News) query.uniqueResult();
//再进行修改
Transaction tx = session.beginTransaction();
n.setContent("update_content5");
session.saveOrUpdate(n);
tx.commit();
session.close();
System.out.println(n);
}
//删除News
@Test
public void deteleNews(){
Session session = HibernateSessionFactory.getSession();
Query query = session.createQuery("from News where id=?");
query.setParameter(0, 4);
News n = (News) query.uniqueResult();
Transaction tx = session.beginTransaction();
session.delete(n);
tx.commit();
session.close();
}
}
小结:“查”的实现是通过查询hql语句实现的。
附:Oracle创建序列seq_news及相应的自动增长触发器
create sequence seq_news;
CREATE OR REPLACE TRIGGER "SCOTT"."trigger_news"
before insert on "SCOTT"."NEWS_TABLE"
for each row
begin
if inserting then
if :NEW."ID" is null then
select seq_news.nextval into :NEW."ID" from dual;
end if;
end if;
end;
/
ALTER TRIGGER "SCOTT"."trigger_news" ENABLE;