第一种:只是用hibernate.propeties来配置数据库的连接参数(一般不推荐此种方式,因为每次都要在代码中手动配置太过于麻烦)
在src目录下建立hibernate.properties(因为hibernate识别机制,必须这样命名):
#hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
#hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=jdbc:mysql://127.0.0.1:3306/example_db
hibernate.connection.username=root
hibernate.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 {
@Test
public 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 exception
e.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 {
@Test
public void addPerson(){
Person person=new Person(111, "小铧", "男", new Date());
Session session=null;
try{
//创建configure配置文件hibernate.properties
Configuration cfg=new Configuration();
//加载映射文件hibernate.cfg.xml
cfg.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 exception
e.printStackTrace();
}finally{
session.close();
}
}
}