天天看點

02. SessionFactory對象的建立方式和Property的使用SessionFactory對象的建立方式和Property的使用

SessionFactory對象的建立方式和Property的使用

Hibernate 5.x建立SessionFactory

/*建立Configuration對象,并讀取指定的Hibernate核心配置檔案*/
Configuration config=new Configuration();
config.configure("hibernate.cfg.xml");

/*建立SessionFactory對象,已不建議被使用*/
//SessionFactory factory=config.buildSessionFactory();

/*5.2版本中建立SessionFactory的建議方法*/
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();  
SessionFactory factory = new MetadataSources(serviceRegistry).buildMetadata().buildSessionFactory();

/*建立Session對象,也是在此處獲得資料庫的連接配接*/
Session session=factory.openSession();
           

Property的使用

中文屬性在英文中有兩個單詞:property和attribute,這兩個單詞在我們使用時是有指定差別的。

Hibernate的映射檔案

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.li.pojo">
    <class name="Student" table="STU_INFO">
        <id name="id" type="string" column="STU_NO">
            <generator class="uuid" />
        </id>       
        <property name="name" type="string" column="STU_NAME"></property>
        <property name="gender" type="string" column="STU_GENDER"></property>
        <property name="age" type="int" column="STU_AGE"></property>
    </class>
</hibernate-mapping>
           

POJO類

package com.li.pojo;

import java.io.Serializable;

public class Student implements Serializable{

    private static final long serialVersionUID = -L;

    private String id;
    private String name;
    private Integer age;
    private String gender;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }


}
           

實際上,這個POJO類的成員變量(id、name、age、gender)也叫屬性,但是應該對應的單詞為attribute,而成員變量的setter和getter方法名稱除去get或set再将首字母小寫(駝峰命名規則)所得到的名稱,對應的才是property(此處也為id、name、age、gender),映射檔案中配置的property正是getter和setter方法而不是成員變量。

如果我們在映射檔案中将一個屬性(property)的name寫錯,如 “gender” 變成 “gedner”,那麼程式在運作時報出的異常為 PropertyNotFoundException 異常,後面的資訊為 “could not find a getter/setter fof property gedner”。這也證明了我們上面所說的。

是以在對資料庫進行操作時,會先根據property的名稱去尋找對應的getter和setter方法,而不是去尋找成員變量。

繼續閱讀