首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Hibernate 環境搭建與配置全流程(XML 配置版 Hello World)

     編輯:Java 相關知識

準備工作

  1. 下載 hibernate-release-4.3.5.Final,導入 lib/required 下 10 個核心 JAR。
  2. 創建 Java 項目,配置 User Library 引入上述 JAR。
  3. 導入 MySQL 驅動 mysql-connector-java-5.1.7-bin.jar。
  4. 建庫建表:
    CREATE DATABASE hibernate;
    USE hibernate;
    CREATE TABLE Student(id INT PRIMARY KEY, name VARCHAR(20), age INT);
    

核心配置文件

1. hibernate.cfg.xml

<?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>

2. 實體類 Student.java

public class Student {
    private int id; private String name; private int age;
    // getter/setter 省略
}

3. 映射文件 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 方式適合維護老項目或學習原理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved