Sử dụng Hibernate Tool tạo các Hibernate Entity một cách tự động từ các table

Bài viết được sự cho phép của tác giả Giang Phan

Trong bài viết trước tôi đã giới thiệu với các bạn các Annotation của Hibernate và cách tạo các Entity từ các table của database. Trong bài viết này, tôi sẽ hướng dẫn các bạn có thể tạo tự động ra các Entity mapping database và Annotation code nhanh chóng bằng việc sử dụng công cụ Hibernate Tool.

Chuẩn bị

Công cụ và môi trường phát triển

  • Java 8
  • Eclipse
  • MySQL
  • JBoss / Hibernate Tools
  Hibernate Batch processing
  Hibernate Interceptor & StatementInspector

Xem thêm các việc làm Entity hấp dẫn trên TopDev

Cơ sở dữ liệu

Chúng ta có mộ hình cơ sở quan hệ các table như sau:

Tạo database và chạy sql sau để tạo các bảng sử dụng trong bài viết này. Chẳng hạn tạo database, gp_cms_system.

Cài đặt Hibernate Tool vào Eclipse

Tìm link download Jboss tool tại đây: https://tools.jboss.org/downloads/

Có 2 cách để cài JBoss Tools vào Eclipse, tương tự như cài các plugin Eclipse khác.

  • Cài đặt từ “Update site”.
  • Cài đặt từ Eclipse Marketplace.

Cài đặt từ “Update site”

Help -> Install New Software …

Tại cửa sổ cài đặt chọn Add :

JBoss tools có nhiều công cụ, chúng ta chỉ cần sử dụng Hibernate nên sẽ tìm và cài đặt các Hibernate item.

Các bạn chọn Next -> chọn Accept terms và Finish.

Cài đặt từ Eclipse Marketplace

Help -> Eclipse Marketplace…

Tại cửa sổ “Eclipse Marketplace…”, cài bạn tìm jboss và chọn Install.

JBoss Tools có rất nhiều công cụ, chúng ta chỉ cần chọn “Hibernate Tools”.

Các bạn chọn Next -> chọn Accept terms và Finish.

Để chắc chắn đã cài đặt thành công, trên menu Eclipse chọn: Window -> Perspective -> Open Perspective -> Other…

Chọn Hibernate -> Open.

Kết nối vào Database thông qua “Database Development”

Trên menu Eclipse chọn: Window -> Perspective -> Open Perspective -> Other…

Tạo mới một connection tới cơ sở dữ liệu trên.

Chọn loại cơ sở dữ liệu: trong bài này tôi sẽ kết nối tới cơ sở dữ liệu MySQL.

Thêm Driver cho database MySQL (trường hợp đã có rồi không cần thêm mới).

Tiếp theo cần add MySQL connector:

Nhập các thông tin để kết nối tới database -> nhấn “Test Connection” để đảm bảo rằng việc kết nối tới database là thành công -> OK

Kiểm tra lại cấu trúc database trên “Data Source Explorer”:

Tạo Maven Project

Tạo maven project và trong file pom.xml khai báo thư viện Hibernate 5, và thư viện JDBC tương ứng cho MySQL. Nội dung file pom.xml như sau:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.gpcoder</groupId>
    <artifactId>HibernateTutorial</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
 
    <name>HibernateTutorial</name>
    <url>http://maven.apache.org</url>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
 
    <dependencies>
 
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.10</version>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.4.7.Final</version>
        </dependency>
 
        <!-- MySQL -->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.17</version>
        </dependency>
 
        <!-- Unit Test -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Cấu hình Hibenate

Mở cửa sổ công cụ Hibernate Tools

Trên menu Eclipse chọn: Window -> Perspective -> Open Perspective -> Other… -> Hibernate

Khởi tạo file Hibernate Configuration

Nhấn phải chuột -> chọn “Add Configuration..” để tạo mới file cấu hình Hibernate.

Nhập các thông tin như sau:

Tại (6), chọn Setup… và chọn tạo mới file hibernate.cfg.xml

Nhập vào tên file “hibernate.cfg.xml”, và đặt nó vào thư mục “src/main/java” của Project.

Nhập các thông tin kết nối tới database hoặc lấy từ thông tin kết nối đã khai báo trước đó.

Chọn “Database dialect” tương ứng với loại Database MySQL.

Nhấn Finish -> một file cấu hình Hibernate được tạo ra trong thư mục src/main/java.

Nội dung file hibernate.cfg.xml như sau:

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/gp_cms_system?serverTimezone=UTC</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    </session-factory>
</hibernate-configuration>

Hibernate Configuration được tạo:

Tạo tự động các Entity mapping & Annation codes

Tiếp theo chúng ta sẽ cấu hình cách để công cụ tạo ra các lớp entity từ việc đọc cấu trúc bảng trong Database.

Tại Hibernate Perspective, chọn Hibernate Code Generation Configurations…

Nhấn chuột phải và chọn New Configuration:

Cấu hình Hibernate Generation:

  • (1) : nhập tên cấu hình.
  • (2) : chọn Hibernate Configuration đã tạo ở trên.
  • (3) : chọn thư mục chứa các Entity được tạo.
  • (4) : package chứa các Entity.
  • (6) : tạo file reveng.xml
  • (6) : check các option để Hibernate khởi tạo quan hệ các Entity, Id.

Tạo file reveng.xml, chọn (5) Setup:

Chọn thư mục chứa file là src/main/java, để tên file mặc định và chọn Next.

Chọn các bảng cần tạo tự động và chọn Finish.

Sau bước này, chúng ta sẽ có một file reveng.xml trong thư mục src/main/java.

Tiếp theo, chọn Tab Exporters và thiết lập tạo tự động các Entity mapping và Annotation code:

  • (1) : Tạo java class sử dụng Java 5 syntax và chuẩn EJP3 Annotation.
  • (2) : Tạo Entity java class và các Annotation.
  • (3) : Tạo các mapping database.

Kết quả sau khi Generate thành công:

Nội dung của một vài class được Generate tự động:

Category.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
package com.gpcoder.entities;
// Generated Nov 26, 2019 1:41:36 AM by Hibernate Tools 4.3.5.Final
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
 * Category generated by hbm2java
 */
@Entity
@Table(name = "category", catalog = "gp_cms_system")
public class Category implements java.io.Serializable {
    private long id;
    private String name;
    private Set<Post> posts = new HashSet<Post>(0);
    public Category() {
    }
    public Category(long id) {
        this.id = id;
    }
    public Category(long id, String name, Set<Post> posts) {
        this.id = id;
        this.name = name;
        this.posts = posts;
    }
    @Id
    @Column(name = "id", unique = true, nullable = false)
    public long getId() {
        return this.id;
    }
    public void setId(long id) {
        this.id = id;
    }
    @Column(name = "name")
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name = name;
    }
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "category")
    public Set<Post> getPosts() {
        return this.posts;
    }
    public void setPosts(Set<Post> posts) {
        this.posts = posts;
    }
}

Post.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package com.gpcoder.entities;
// Generated Nov 26, 2019 1:41:36 AM by Hibernate Tools 4.3.5.Final
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
 * Post generated by hbm2java
 */
@Entity
@Table(name = "post", catalog = "gp_cms_system")
public class Post implements java.io.Serializable {
    private long id;
    private Category category;
    private User user;
    private String title;
    private String content;
    public Post() {
    }
    public Post(long id) {
        this.id = id;
    }
    public Post(long id, Category category, User user, String title, String content) {
        this.id = id;
        this.category = category;
        this.user = user;
        this.title = title;
        this.content = content;
    }
    @Id
    @Column(name = "id", unique = true, nullable = false)
    public long getId() {
        return this.id;
    }
    public void setId(long id) {
        this.id = id;
    }
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "category_id")
    public Category getCategory() {
        return this.category;
    }
    public void setCategory(Category category) {
        this.category = category;
    }
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    public User getUser() {
        return this.user;
    }
    public void setUser(User user) {
        this.user = user;
    }
    @Column(name = "title")
    public String getTitle() {
        return this.title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    @Column(name = "content")
    public String getContent() {
        return this.content;
    }
    public void setContent(String content) {
        this.content = content;
    }
}

Tài liệu tham khảo:

Bài viết gốc được đăng tải tại gpcoder.com

Có thể bạn quan tâm:

Xem thêm Việc làm IT hấp dẫn trên TopDev