您的位置:首页 > 运维架构

properties类读取配置文件

2007-05-19 10:48 302 查看
package com.wyq.hibernate;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Example {
//建立一个静态的工场对象
private static SessionFactory session_factory = null;
//建立一个存储配置文件的对象--properties
private static Properties pops=new Properties();
//取得配置文件路径,配置文件存放在class路径下
private static String path=Example.class.getClassLoader().getResource("").getPath()+"hibernate.properties";
//建立一个静态方法,用来读取配置文件---hibernate.properties,在static静态方法中只能引用静态变量
static{
try{
String s=path.substring(1,path.length());
//读取配置文件
InputStream stream= new FileInputStream(s);
//如果配置文件和类放在同一个目录下,这种情况不建议使用
InputStream streams=Example.class.getResourceAsStream("hibernate.properties");
//将配置文件存储在pops中
pops.load(stream);
//建立配置文件管理对象
Configuration cfg=new Configuration();
//将Person添加到cfg中,类似于将xxx.hbm.xml写在hibernate.hbm.xml中
cfg.addClass(Person.class);
//将pops添加到cfg中,就是hiberante.hbm.xml
cfg.setProperties(pops);
//建立对象工厂
session_factory=cfg.buildSessionFactory();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args)throws HibernateException{
Person person=new Person();
person.setName("wyq");
person.setEmail("hibernate.com.cn");

//取得一个session,获得连接
Session session=session_factory.openSession();
//定义一个事务
Transaction tx=null;
try{
//开启一个事务
tx=session.beginTransaction();
//具体业务操作
session.save(person);
tx.commit();

}catch(HibernateException ex){
if(tx!=null){
tx.rollback();
}
}
finally{
session.close();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: