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

Hibernate 4.3 註解版快速入門:基於 Eclipse + Tomcat 8 + MySQL 完整實戰

     編輯:Java 綜合教學

環境準備

  • IDE:Eclipse MARS.2 (4.5.2)
  • Hibernate:4.3.6.Final
  • Web 容器:Tomcat 8.0
  • 數據庫:MySQL 5.6.19
  • JDBC 驅動:mysql-connector-java-5.1.30-bin.jar

項目創建與依賴導入

  1. 新建 Dynamic Web Project:firsthibernate
  2. 複製 hibernate/lib/required/*.jar + JDBC 驅動 → WEB-INF/lib
  3. 複製 hibernate/project/etc/hibernate.cfg.xml → src 目錄

實體類:JPA 註解映射

@Entity
@Table(name = "tb_cat")
public class Cat {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @Column(name = "name")
    private String name;

    @Column(name = "description")
    private String description;

    @ManyToOne
    @JoinColumn(name = "mother_id")
    private Cat mother;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "birthday")
    private Date birthday;
    // Getter/Setter...
}

關鍵註解說明:

  • @Entity:標識持久化實體
  • @Table:指定表名
  • @Id + @GeneratedValue:主鍵自增
  • @ManyToOne + @JoinColumn:多對一關聯
  • @Temporal:日期類型映射

核心配置文件

<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>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">create</property>
        <property name="current_session_context_class">thread</property>
        <mapping class="com.levice.firsthibernate.bean.Cat"/>
    </session-factory>
</hibernate-configuration>

關鍵屬性: hbm2ddl.auto=create 啟動時自動建表(僅開發環境使用)。

數據庫初始化

CREATE DATABASE hibernate;

SessionFactory 工具類

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new AnnotationConfiguration()
                .configure().buildSessionFactory();
        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

註:Hibernate 4.3 使用 AnnotationConfiguration,5.x+ 已棄用,改用 Configuration。

測試驗證

public class CatTest {
    public static void main(String[] args) {
        Cat mother = new Cat();
        mother.setName("Mother White");
        mother.setDescription("This is mother cat");
        mother.setBirthday(new Date());

        Cat kitty = new Cat();
        kitty.setMother(mother);
        kitty.setName("Kitty");

        Cat tom = new Cat();
        tom.setMother(mother);
        tom.setName("Tom");

        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();
        session.persist(mother);
        session.persist(kitty);
        session.persist(tom);

        List cats = session.createQuery("from Cat").list();
        // 遍歷輸出...
        tx.commit();
        session.close();
    }
}

運行結果驗證

Swing 彈窗展示查詢結果

控制台 SQL 輸出

Hibernate: create table tb_cat (id integer not null auto_increment, ...)
Hibernate: insert into tb_cat (birthday, description, mother_id, name) values (?, ?, ?, ?)
Hibernate: select cat0_.id as id1_0_, ... from tb_cat cat0_

自動建表、外鍵關聯、數據插入、查詢全流程無需手寫 SQL。

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