Hibernate的配置的讀取

hibernate從配置文件中讀取和數據庫鏈接有關的信息有的兩種格式
2008-04-27 21:08

hibernate從配置文件中讀取和數據庫鏈接有關的信息有兩種格式,一種是XML文件配置,一種是屬性文件配置即properties文件來配置,因爲配置文件的不一樣致使使用hibernate api的時候會有微小差異,如今以hibernate2版本爲例分別具體說明java

1. 使用xml文件配置,文件格式通常爲.cfg.xml,下面列舉出了一個簡要的配置mysql

<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 2.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-2.0.dtd">sql

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>數據庫

    <session-factory>
        <property name="connection.username">root</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/mydb</property>
        <property name="dialect">net.sf.hibernate.dialect.MySQLDialect</property>
        <property name="myeclipse.connection.profile">mydb</property>
        <property name="connection.password">root</property>
        <property name="connection.driver_class">org.gjt.mm.mysql.Driver</property>
    
   <mapping resource="com/beans/customer.hbm.xml"/>
    </session-factory>api

</hibernate-configuration>session

其中connection.username制定用戶名,connection.url制定數據庫鏈接的url,dialect制定數據庫方言,connection.password制定制定用戶的密碼,connection.driver_class制定驅動類,<mapping resource="com/beans/customer.hbm.xml"/>制定其中一個orm映射文件的位置,app

下面列舉出customer.hbm.xml的一個樣例eclipse

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
    
<hibernate-mapping>
<class name = "com.beans.Customer" table="customers" >
   <id name = "id" column="id" type = "long">
    <generator class="increment"/>
   </id>
   <property name="name" column = "name" type = "string" not-null="true" />
   <property name="email" column = "email" type = "string" not-null="true" />
   <property name="password" column = "password" type = "string" not-null="true" />
   <property name="phone" column = "phone" type = "int" />
   <property name="address" column = "address" type = "string" />
   <property name="sex" column = "sex" type = "character" />
</class>
</hibernate-mapping>ui

同時須要創建數據庫對應的java類文件this

import java.io.Serializable;

public class Customer implements Serializable{
private Long id;
private String name;
private String email;
private String password;
private int phone;
private char sex;
private String address;
public Long getId() {
   return id;
}
public void setId(Long id) {
   this.id = id;
}
public String getName() {
   return name;
}
public void setName(String name) {
   this.name = name;
}
public String getEmail() {
   return email;
}
public void setEmail(String email) {
   this.email = email;
}
public String getPassword() {
   return password;
}
public void setPassword(String password) {
   this.password = password;
}
public int getPhone() {
   return phone;
}
public void setPhone(int phone) {
   this.phone = phone;
}
public char getSex() {
   return sex;
}
public void setSex(char sex) {
   this.sex = sex;
}
public String getAddress() {
   return address;
}
public void setAddress(String address) {
   this.address = address;
}
}

使用hibernate api時具體示例代碼以下

public class BusinessService {
public static SessionFactory sessionFactory;
static{
   Configuration config = new Configuration();
   try {
//    config.addClass(Customer.class);
    sessionFactory = config.configure().buildSessionFactory();
   
      } catch (MappingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }catch (HibernateException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } 
  
}
public static void main(String[] args) {
   Class c = Customer.class;
   Customer customer = new Customer();
   customer.setName("aaa");
   customer.setPassword("1234");
   customer.setEmail("alei_1304@163.com");
   customer.setPhone(1234);
   customer.setAddress("北京市中關村");
   customer.setSex('M');
   try {
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    session.save(customer);
    tx.commit();
    session.close();
   } catch (HibernateException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  
}
}

其中採用xml文件配置,在初始化SessionFactory實例的時候須要採用 new Configuration().configure().buildSessionFactory(),若是直接使用new Configuration().buildSessionFactory()會報異常java.lang.UnsupportedOperationException: The user must supply a JDBC connection

因爲必須在xml配置文件中制定 <mapping resource="com/beans/customer.hbm.xml"/>,因此在程序中無需再使用config.addClass(Customer.class),不然會致使異常net.sf.hibernate.MappingException: Error reading resource: com/beans/customer.hbm.xml
at net.sf.hibernate.cfg.Configuration.addResource(Configuration.java:340)
at net.sf.hibernate.cfg.Configuration.doConfigure(Configuration.java:1027)
at net.sf.hibernate.cfg.Configuration.doConfigure(Configuration.java:983)
at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:911)
at net.sf.hibernate.cfg.Configuration.configure(Configuration.java:897)
at com.business.BusinessService.<clinit>(BusinessService.java:17)
Caused by: net.sf.hibernate.MappingException: duplicate import: Customer

2.採用屬性文件配置數據庫鏈接的信息

須要配置一個屬性文件來制定數據庫鏈接信息,示例以下

hibernate.dialect = net.sf.hibernate.dialect.MYSQLDialect
hibernate.connection.driver_class = com.mysql.jdbc.Driver
hibernate.connection.url = jdbc:mysql://localhost:3306/mydb
hibernate.connection.username = root
hibernate.connection.password = root
hibernate.show_sql = true

orm映射文件和java類文件的配置同上,使用hibernate api示例代碼以下

public class BusinessService {
public static SessionFactory sessionFactory;
static{
   Configuration config = new Configuration();
   try {
    config.addClass(Customer.class);
    sessionFactory = config.buildSessionFactory();
   
      } catch (MappingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }catch (HibernateException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } 
  
}
public static void main(String[] args) {
   Class c = Customer.class;
   Customer customer = new Customer();
   customer.setName("董磊");
   customer.setPassword("1234");
   customer.setEmail("alei_1304@163.com");    customer.setPhone(1234);    customer.setAddress("北京市中關村");    customer.setSex('M');    try {     Session session = sessionFactory.openSession();     Transaction tx = session.beginTransaction();     session.save(customer);     tx.commit();     session.close();    } catch (HibernateException e) {     // TODO Auto-generated catch block     e.printStackTrace();    }    } }

相關文章
相關標籤/搜索