说明:数据库: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;

hibernate.cfg.xml配置(Oracle+c3p0)的更多相关文章

  1. hibernate.cfg.xml 配置(摘录)

    配置文件中映射元素详解 对象关系的映射是用一个XML文档来说明的.映射文档可以使用工具来生成,如XDoclet,Middlegen和AndroMDA等.下面从一个映射的例子开始讲解映射元素,映射文件的 ...

  2. 用hibernate.properties代替hibernate.cfg.xml配置常用的属性

    我们使用hibernate时经常在hibernate.cfg.xml文件中配置数据库连接的相关属性,是否显示sql语句,数据库的方言等,这些配置其实也可以在.properties文件中配置.现在我把这 ...

  3. hibernate.cfg.xml配置

    hibernate.hbm2ddl.auto 配置: create:每次加载hibernate时都会删除上一次的生成的表,然后根据你的model类再重新来生成新表,哪怕两次没有任何改变也要这样执行,这 ...

  4. hibernate.cfg.xml 配置SQL server,MySQL,Oracle

    1.连接SQL server <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hiberna ...

  5. hibernate4配置文件hibernate.cfg.xml配置详解

    <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE hibernate-configurat ...

  6. Hibernate hibernate.cfg.xml配置

    数据库连接<required>: <property name="hibernate.connection.driver_class"> com.mysql ...

  7. hibernate4.3.5,Final hibernate.cfg.xml的配置

    今天是接触hibernate的第二天,用来练习的是hibernate最新的版本hibernate-release-4.3.5.Final 要使用hibernate,则先要引入它的jar包,要引入的ja ...

  8. spring applicationContext.xml和hibernate.cfg.xml设置

    applicationContext.xml配置 <?xml version="1.0" encoding="UTF-8"?> <beans ...

  9. hibernate.cfg.xml配置文件和hbm.xml配置文件

    http://blog.sina.com.cn/s/blog_a7b8ab2801014m0e.html hibernate.cfg.xml配置文件格式 <?xml version=" ...

随机推荐

  1. Quartz Scheduler(2.2.1) - Usage of SimpleTrigger

    SimpleTrigger should meet your scheduling needs if you need to have a job execute exactly once at a ...

  2. Linux 命令 - su: 以其他用户和组 ID 的身份来运行 shell

    在 shell 会话状态下,使用 su 命令将允许你假定为另一个用户的身份,既可以以这个用户的 ID 来启动一个新的 shell 会话,也可以以这个用户的身份来发布一个命令. 命令格式 su [OPT ...

  3. 随笔之Android平台上的进程调度探讨

    http://blog.csdn.net/innost/article/details/6940136 随笔之Android平台上的进程调度探讨 一由来 最近在翻阅MediaProvider的时候,突 ...

  4. ASSERT报错:error C2664: “AfxAssertFailedLine”: 不能将参数 1 从“TCHAR []”转换为“LPCSTR”

    转载请注明来源:崨雁嫀筝 http://www.cnblogs.com/xuesongshu 这个错误是我在把tinyxml修改为宽字符(Unicode)版本时候遇到的问题,我首先按关键字把所有有ch ...

  5. 我的EntityFramework(2):简单的数据查询

    原文:我的EntityFramework(2):简单的数据查询 在上一篇博文中,已经搭建了基本的框架,接下来就进行简单的数据查询,这里主要用了Linq 常见的数据集查询 var companyList ...

  6. stl中的map数据类型

    1.1 STL map 1.1.1 背景 关联容器使用键(key)来存储访问读取元素,而顺序容器则通过元素在容器中的位置存储和访问元素. 常见的顺序容器有:vector.list.deque.stac ...

  7. iOS开发——开发者官网注册新设备

    1.第一步登陆苹果开发者中心官网,进入证书栏后如下图:点击All 或者如果是iPhone设备直接点击iPhone也行. 然后点击右上角的[+]号

  8. Xcode 真机无法调试

    关于只能在模拟器上测试不能在真机测试的问题 2. 在 buildSetting 里面搜索bitcode,更改为 No 即可.

  9. 移动web屏幕适配方案

    刚进部门就被拉去趟移动端Web的浑水,视觉稿是按照640px设计的.那如何做屏幕适配呢?当然想到的第一方法就是问前辈了,问他们之前怎么做的,前辈说直接按视觉稿来,我说640太大了,他说除以2啊,按32 ...

  10. 关于arcgis发布wfs问题

    博客地址http://www.cnblogs.com/shizhongtao/p/3453594.html 官方文档中有这么一段描述: 从地图创建 WFS 服务 您 可以从 ArcMap 地图文档 ( ...