hibernate中另外两种配置文件方式的配置

来源:互联网 发布:神经网络编程入门 pdf 编辑:程序博客网 时间:2024/05/16 15:47

第一种:只是用hibernate.propeties来配置数据库的连接参数(一般不推荐此种方式,因为每次都要在代码中手动配置太过于麻烦)

在src目录下建立hibernate.properties(因为hibernate识别机制,必须这样命名):

#hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect#hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialecthibernate.dialect=org.hibernate.dialect.MySQLDialecthibernate.connection.driver_class=com.mysql.jdbc.Driverhibernate.connection.url=jdbc:mysql://127.0.0.1:3306/example_dbhibernate.connection.username=roothibernate.connection.password=04010

接着写个例子测试成不成功:

package example.dao;import java.util.Date;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.junit.Test;import example.domain.Person;public class PersonDao2 {@Testpublic void addPerson(){Person person=new Person(111, "小红", "女", new Date());Session session=null;try{//创建configure配置文件Configuration cfg=new Configuration();//手动加载映射文件cfg.addResource("example/domain/Person.hbm.xml");//创建sessionFactory工厂对象SessionFactory sessionFactory=cfg.buildSessionFactory();//创建session对象session= sessionFactory.openSession();//开启事务Transaction ts= session.getTransaction();//开始事务ts.begin();//保存对象到数据库session.save(person);ts.commit();}catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally{session.close();}}}

第二种配置方式(hibernate.cfg.xml和hibernate.properties的集合):

src下的hibernate.properties的配置参数不变,只改变hibernate.cfg.xml,也就是hibernate.cfg.xml只存放映射文件,hibernate.properties存放配置参数。

改变如下:

<?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"><hibernate-configuration><session-factory><!-- 以下是配置加载映射文件 --><mapping resource="example/domain/Person.hbm.xml"/></session-factory></hibernate-configuration>

package example.dao;import java.util.Date;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.junit.Test;import example.domain.Person;public class PersonDao2 {@Testpublic void addPerson(){Person person=new Person(111, "小铧", "男", new Date());Session session=null;try{//创建configure配置文件hibernate.propertiesConfiguration cfg=new Configuration();//加载映射文件hibernate.cfg.xmlcfg.configure();//创建sessionFactory工厂对象SessionFactory sessionFactory=cfg.buildSessionFactory();//创建session对象session= sessionFactory.openSession();//开启事务Transaction ts= session.getTransaction();//开始事务ts.begin();//保存对象到数据库session.save(person);ts.commit();}catch (Exception e) {// TODO: handle exceptione.printStackTrace();}finally{session.close();}}}


0 0
原创粉丝点击