hibernate-release-4.3.5.Final,導入 lib/required 下 10 個核心 JAR。mysql-connector-java-5.1.7-bin.jar。CREATE DATABASE hibernate;
USE hibernate;
CREATE TABLE Student(id INT PRIMARY KEY, name VARCHAR(20), age INT);
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"https://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">123456</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="show_sql">true</property>
<mapping resource="com/huxing/hibernate/model/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Student.javapublic class Student {
private int id; private String name; private int age;
// getter/setter 省略
}
Student.hbm.xml<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.huxing.hibernate.model">
<class name="Student" table="student">
<id name="id" column="id"/>
<property name="name" column="name" type="string"/>
<property name="age" column="age" type="int"/>
</class>
</hibernate-mapping>
public class StudentTest {
public static void main(String[] args) {
Student s = new Student(); s.setId(123); s.setName("hello hibernate!"); s.setAge(32);
Configuration cfg = new Configuration().configure();
SessionFactory sf = cfg.buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
session.close(); sf.close();
}
}
MappingNotFoundException:檢查 .hbm.xml 路徑是否在 classpath 根目錄,cfg.xml 中 mapping resource 路徑是否一致。Dialect not set:必須指定 dialect 屬性。<property name="hbm2ddl.auto">update</property>。新項目建議使用 JPA 標準註解(@Entity, @Table, @Id...) 替代 XML 映射,配合 Spring Data JPA 進一步簡化 DAO 開發。XML 方式適合維護老項目或學習原理。