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 = -510606980498679054L;
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方法,而不是去寻找成员变量。