使用 XML 的简单 hibernate 示例
要使用 XML 为配置设置一个简单的 hibernate 项目,你需要 3 个文件,hibernate.cfg.xml,每个实体的 POJO 和每个实体的 EntityName.hbm.xml。以下是使用 MySQL 的示例:
hibernate.cfg.xml
<?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>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost/DBSchemaName
</property>
<property name="hibernate.connection.username">
testUserName
</property>
<property name="hibernate.connection.password">
testPassword
</property>
<!-- List of XML mapping files -->
<mapping resource="HibernatePractice/Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
DBSchemaName,testUserName 和 testPassword 都将被替换。如果它在包中,请确保使用完整的资源名称。
Employee.java
package HibernatePractice;
public class Employee {
private int id;
private String firstName;
private String middleName;
private String lastName;
public Employee(){
}
public int getId(){
return id;
}
public void setId(int id){
this.id = id;
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public String getMiddleName(){
return middleName;
}
public void setMiddleName(String middleName){
this.middleName = middleName;
}
public String getLastName(){
return lastName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
}
Employee.hbm.xml
<hibernate-mapping>
<class name="HibernatePractice.Employee" table="employee">
<meta attribute="class-description">
This class contains employee information.
</meta>
<id name="id" type="int" column="empolyee_id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name" type="string"/>
<property name="middleName" column="middle_name" type="string"/>
<property name="lastName" column="last_name" type="string"/>
</class>
</hibernate-mapping>
同样,如果类在包中,则使用完整的类名 packageName.className。
拥有这三个文件后,你就可以在项目中使用 hibernate 了。