Tạo database table tự động từ Hibernate Entity

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

Trong bài trước tôi đã hướng dẫn các bạn sử dụng các Annotation và mapping type để tạo các Hibernate Entity cho các table trong database. Giả sử bây giờ chúng ta không có database từ trước, khách hàng chỉ cung cấp source code với các Hibernate Entity. Để chạy được ứng dụng chúng ta cần phải có database để lưu trữ dữ liệu. Chúng ta, có thể tạo database và tạo từng table cũng như các quan hệ của nó một cách thủ công. Tuy nhiên, cách làm này tốn rất nhiều công sức, dễ sai sót và không cần thiết.

  Hibernate Criteria Query Language (HCQL)
  Hibernate Batch processing

Xem thêm các việc làm Entity lương cao trên TopDev

Với Hibernate, nó đã cung cấp một tính năng rất tiện lợi và dễ dàng cấu hình để tạo các table một cách tự động dựa vào các Hibernate Entity. Chúng ta sẽ cùng tìm hiểu trong bài viết này.

Các bước thực hiện khá đơn giản:

  • Tạo các Hibernate Entity với đầy đủ các Annotation và mapping type.
  • Tạo hibernate configuration file.
  • Tạo Hibernate connection class để giao tiếp với database.

Tạo các Hibernate Entity

Mô hình cơ sở quan hệ các table như sau:

Tương ứng với database, chúng ta có các Hibernate Entity:

Role.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;


import lombok.Data;


@Data
@Entity
@Table
public class Role {


    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;


    @Column
    private String name;
    
    @ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles")
    private Set<User> users;
}

User.java

import java.util.Date;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;

import lombok.Data;

@Data
@Entity(name = "User")
@Table(name = "user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String fullname;

    @Column(nullable = false, length = 255, unique = true)
    private String username;

    @Column(nullable = false)
    private String password;

    @Column(name = "created_at")
    @Temporal(value = TemporalType.TIMESTAMP)
    private Date createdAt;

    @Column(name = "modified_at")
    @Temporal(value = TemporalType.TIMESTAMP)
    private Date modifiedAt;

    @Transient
    private String additionalPropery;
    
    @OneToOne(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
    private UserProfile userProfile;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
    @OrderBy("title")
    private Set<Post> posts;
    
    @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @JoinTable(name = "user_roles",
        joinColumns = { @JoinColumn(name = "user_id", nullable = false, updatable = false) },
        inverseJoinColumns = { @JoinColumn(name = "role_id", nullable = false, updatable = false) })
    @OrderBy("name")
    private Set<Role> roles;
}

UserProfile.java

import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;

import lombok.Data;

@Data
@Entity
@Table(name = "user_profile")
public class UserProfile {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String address;

    private Integer gender;

    @OneToOne(fetch = FetchType.LAZY)
    @PrimaryKeyJoinColumn(name = "user_id", foreignKey = @ForeignKey(name = "fk_user_profile"))
    private User user;
}

Category.java

import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;

import lombok.Data;

@Data
@Entity
@Table
public class Category {

    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column
    private String name;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "category")
    @OrderBy("title")
    private Set<Post> posts;
}

Post.java

import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import lombok.Data;

@Data
@Entity
@Table
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String title;

    private Integer content;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false,
        foreignKey = @ForeignKey(name = "fk_post_user"))
    private User user;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "category_id", nullable = false,
        foreignKey = @ForeignKey(name = "fk_post_category"))
    private Category category;
}

Tạo hibernate configuration file

Để tạo một cách tự động chúng ta cần thêm một property hibernate.hbm2ddl.auto trong Hibernate confirugation file.

Cấu hình hbm2ddl có nghĩa là Hibernate mapping để tạo lược đồ DDL (Data Definition Language – ngôn ngữ định nghĩa dữ liệu) một cách tự động.

Cấu hình này có thể có các giá trị sau:

  • create : Nếu giá trị này được sử dụng, Hibernate sẽ xóa tất cả các table và structure. Sau đó, tạo lại các table mới dựa vào Hibernate Entity. Lưu ý khi sử dụng giá trị này, các dữ liệu của chúng ta sẽ bị mất và không thể phục hồi lại được.
  • validate : Nếu giá trị này được sử dụng, Hibernate chỉ validate các table structure ở đó các table và column tồn tại hay không. Nếu table không tồn tại, Hibernate sẽ throw một Exception.
  • update : Nếu giá trị này được sử dụng, Hibernate sẽ kiểm tra table tồn tại hay không. Nếu không tồn tại, table mới sẽ được tạo. Tương tự với column, nếu column không tồn tại, Hibernate sẽ tạo một column mới. Với giá trị update này, các table sẽ không được xóa nên dữ liệu của chúng ta không bị mất.
  • create-drop : Nếu giá trị này được sử dụng, Hibernate sẽ tạo các table structure để thực hiện các thao tác và các table structure sẽ được xóa sau khi các thao tác đã hoàn thành (SessionFactory đã đóng). Giá trị này thích hợp khi viết Unit test cho Hibernate code.

Tạo file hibernate.cfg.xml trong thư mục src\main\resources của project với nội dung như sau:

<?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>
        <!-- Database setting -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/gp_system_auto?serverTimezone=UTC&amp;useUnicode=true&amp;characterEncoding=utf8</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>
        
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">4</property>

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!-- Enable Hibernate's automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Show all executed SQL to console -->
        <property name="show_sql">true</property>
        
        <!-- Automatically validates or exports schema DDL to the database when the SessionFactory is created -->
        <!-- validate, create, update, create-drop -->
        <property name="hibernate.hbm2ddl.auto">create-drop</property>

        <!-- Entity mapping -->
        <mapping class="com.gpcoder.models.User" />
        <mapping class="com.gpcoder.models.Role" />
        <mapping class="com.gpcoder.models.UserProfile" />
        <mapping class="com.gpcoder.models.Category" />
        <mapping class="com.gpcoder.models.Post" />
        
    </session-factory>
</hibernate-configuration>

Tạo Hibernate connection class

HibernateUtils.java

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtils {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private HibernateUtils() {
        super();
    }

    private static SessionFactory buildSessionFactory() {
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() //
                .configure() // Load hibernate.cfg.xml from resource folder by default
                .build();
        Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build();
        return metadata.getSessionFactoryBuilder().build();
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void close() {
        getSessionFactory().close();
    }
}

Tạo chương trình truy vấn các Entity trên để kiểm tra kết quả:

import org.hibernate.Session;

import com.gpcoder.models.Category;
import com.gpcoder.utils.HibernateUtils;

public class HibernateExample2 {

public static void main(String[] args) {
        
        try (Session session = HibernateUtils.getSessionFactory().openSession();) {
            // Begin a unit of work
            session.beginTransaction();

            // Insert user
            Category cat = new Category();
            cat.setName("cat " + System.currentTimeMillis());
            System.out.println("Cat id = " + session.save(cat));
            
            // Commit the current resource transaction, writing any unflushed changes to the database.
            session.getTransaction().commit();
        }
    }
}

Tạo database gp_system_auto và chạy chương trình trên. Chúng ta có output chương trình như sau

INFO: HHH000115: Hibernate connection pool size: 4 (min=1)
Dec 15, 2019 9:58:11 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate: drop table if exists Category
Dec 15, 2019 9:58:13 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@22d1886d] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: drop table if exists Post
Hibernate: drop table if exists Role
Hibernate: drop table if exists user
Hibernate: drop table if exists user_profile
Hibernate: drop table if exists user_roles
Hibernate: create table Category (id bigint not null auto_increment, name varchar(255), primary key (id)) engine=MyISAM
Dec 15, 2019 9:58:13 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@68ba310d] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table Post (id bigint not null auto_increment, content integer, title varchar(255), category_id bigint not null, user_id bigint not null, primary key (id)) engine=MyISAM
Hibernate: create table Role (id bigint not null auto_increment, name varchar(255), primary key (id)) engine=MyISAM
Hibernate: create table user (id bigint not null auto_increment, created_at datetime, fullname varchar(255), modified_at datetime, password varchar(255) not null, username varchar(255) not null, primary key (id)) engine=MyISAM
Hibernate: create table user_profile (id bigint not null auto_increment, address varchar(255), gender integer, primary key (id)) engine=MyISAM
Hibernate: create table user_roles (user_id bigint not null, role_id bigint not null, primary key (user_id, role_id)) engine=MyISAM
Hibernate: alter table user add constraint UK_sb8bbouer5wak8vyiiy4pf2bx unique (username)
Hibernate: alter table Post add constraint fk_post_category foreign key (category_id) references Category (id)
Hibernate: alter table Post add constraint fk_post_user foreign key (user_id) references user (id)
Hibernate: alter table user_roles add constraint FKbhgxpici80n5kpvs65q90ou14 foreign key (role_id) references Role (id)
Hibernate: alter table user_roles add constraint FK55itppkw3i07do3h7qoclqd4k foreign key (user_id) references user (id)
Hibernate: insert into Category (name) values (?)
Cat id = 1

Như bạn thấy, Hibernate tự generate các câu lệnh tạo table, có ràng buộc và sau đó thực thi các sql cần thiết.

Kiểm tra database, bạn sẽ thấy các table được tạo ra như sau:

Các bạn lưu ý, trong ví trên tôi sử dụng cấu hình hibernate.hbm2ddl.auto=create-drop . Các bạn có thể thay đổi các giá trị khác và chạy thử để kiểm tra kết quả.

Bài viết đến đây là hết. Cám ơn các bạn đã quan tâm và theo dõi.

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