Hibernate代码的java理解输出
我刚开始使用hibernate我已经编写了我的第一个hibernate代码,但我无法理解与之相关的输出代码是:
持久性类:
package com.andoi.hibernate;
public class Customers {
public int cid; //Primary key
public String cname;
public String email;
public long phone;
public Customers(){
System.out.println("Customers->dc");
}
public Customers(String cname,String email,long phone){
System.out.println("Customers->three arg");
this.cname=cname;
this.email=email;
this.phone=phone;
}
public int getCid() {
System.out.println("getCid()");
return cid;
}
public void setCid(int cid) {
System.out.println("setCid()");
this.cid = cid;
}
public String getCname() {
System.out.println("getCname()");
return cname;
}
public void setCname(String cname) {
System.out.println("setCname()");
this.cname = cname;
}
public String getEmail() {
System.out.println("getEmail()");
return email;
}
public void setEmail(String email) {
System.out.println("setEmail()");
this.email = email;
}
public long getPhone() {
System.out.println("getPhone()");
return phone;
}
public void setPhone(long phone) {
System.out.println("setPhone()");
this.phone = phone;
}
}
hibernate映射文档:
<hibernate-mapping package="com.andoi.hibernate">
<class name="Customers" table="jlccustomers">
<id name="cid" column="cid" type="int">
<generator class="increment"/>
</id>
<property name="cname" column="cname" type="string"/>
<property name="email" column="email" type="string"/>
<property name="phone" column="phone" type="long"/>
</class>
</hibernate-mapping>
客户端代码:
package com.andoi.hibernate;
import org.hibernate.cfg.*;
import org.hibernate.*;
public class SaveInTable {
public static void main(String[] args){
Transaction tx=null;
try{
Configuration cfg=new Configuration();
cfg=cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();
Session session=sf.openSession();
tx=session.beginTransaction();
}catch(HibernateException e){
if(tx!=null)
tx.rollback();
e.printStackTrace();
}
}
}
输出为:
Customers->dc
getCid()
Customers->dc
getCname()
getEmail()
getPhone()
setCname()
setEmail()
setPhone()
我的问题是为什么要创建持久性类对象,并调用getter和setter
# 1 楼答案
创建会话工厂时,hibernate加载配置文件-
hibernate.cfg.xml
,并解析其中的每一行现在,您将在该配置文件中获得映射文件的详细信息,因此hibernate将解析每个映射文件(*.hbm.xml文件),并尝试验证映射信息是否正确
因此,基于
hbm
文件中的映射信息,它会检查Java类是否存在,并加载该类的实例,然后用Java类中可用的字段验证hibernate映射文件中映射的每个属性,并确保每个字段都有适当的setter和getter方法。这就是为什么会看到对Java类的默认构造函数、getter和setter方法的调用。假设Java类中有一个字段,其映射不在hbm
文件中,那么hibernate不会查找该字段及其对应的getter&;setter方法