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

Hibernate 註解配置入門:從實體映射到 SessionFactory 建立

     編輯:Java 綜合教學

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:3306/hibernate</property>
    <property name="connection.username">root</property>
    <property name="connection.password">123456</property>

    <!-- 方言與顯示 SQL -->
    <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
    <property name="show_sql">true</property>
    <property name="hbm2ddl.auto">create</property>

    <!-- 註解實體類 -->
    <mapping class="com.ij34.dao.New"/>
  </session-factory>
</hibernate-configuration>

2. 實體類註解

package com.ij34.dao;
import javax.persistence.*;

@Entity
@Table(name = "test01")
public class New {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String title;
    private String content;
    // getter/setter 省略...
}

3. 測試類:建立 SessionFactory 並持久化

package com.ij34.web;
import org.hibernate.*;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.*;
import com.ij34.dao.New;

public class test01 {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration().configure();
        ServiceRegistry sr = new StandardServiceRegistryBuilder()
                .applySettings(conf.getProperties()).build();
        SessionFactory sf = conf.buildSessionFactory(sr);
        Session session = sf.openSession();
        Transaction tx = session.beginTransaction();

        New n = new New();
        n.setTitle("hello");
        n.setContent("hello world");
        session.save(n);

        tx.commit();
        session.close();
        sf.close();
    }
}

關鍵點提示

  • @Entity 標記實體,@Table 指定表名。
  • @Id + @GeneratedValue 定義主鍵生成策略(此處用自增)。
  • Hibernate 4/5 建議使用 StandardServiceRegistryBuilder 建立註冊表,再構建 SessionFactory。
  • hbm2ddl.auto=create 啟動時自動建表(僅開發測試用)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved