Hibernate入门之创建数据库表

前言

Hibernate 5.1和更早版本至少需要Java 1.6和JDBC 4.0,Hibernate 5.2和更高版本至少需要Java 1.8和JDBC 4.2,从本节开始我们正式进入Hibernate学习,所采用版本为5.4.12.Final稳定版本。

Hibernate创建数据库表

首先我们通过idea常见mven项目,并下载JDBC和Hibernate包以及添加java 8语法支持,包和添加和项目创建如下:


    
        mysql
        mysql-connector-java
        8.0.13
    
    
        org.hibernate
        hibernate-core
        5.4.12.Final
    


    src/main/java
    
        
            org.apache.maven.plugins
            maven-compiler-plugin
            
                8
                8
            
        
    

Hibernate入门之创建数据库表_第1张图片

接下来我们创建如上Student实体

package hibernate.entity;

import javax.persistence.*;

@Entity
public class Student {

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

    @Column
    private String firstName;

    @Column
    private String lastName;

    @Column
    private String email;

    public Student() {

    }

    public Student(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
    }
}

然后在上述资源文件夹resources下创建Hibernate配置文件,如下:

configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

    
        
        com.mysql.cj.jdbc.Driver
        jdbc:mysql://localhost:3306/hibernate_db?serverTimezone=UTC
        root
        root
        
        org.hibernate.dialect.MySQL5Dialect
        
        true
        
        thread
        
        create-drop
        
        5
        20
        10
        5
        -1
        
    

接下来我们创建Hibernate的SessionFactory,以此来进行对象的会话管理,如下:

package hibernate.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

public class HibernateUtil {
    private static StandardServiceRegistry registry;
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
            try {

                // Create registry
                 registry = new StandardServiceRegistryBuilder().configure().build();

                // Create MetadataSources
                MetadataSources sources = new MetadataSources(registry);

                // Create Metadata
                 Metadata metadata = sources.getMetadataBuilder().build();

                // Create SessionFactory
                sessionFactory = metadata.getSessionFactoryBuilder().build();

            } catch (Exception e) {
                e.printStackTrace();
                if (registry != null) {
                    StandardServiceRegistryBuilder.destroy(registry);
                }
            }
        }
        return sessionFactory;
    }

    public static void shutdown() {
        if (registry != null) {
            StandardServiceRegistryBuilder.destroy(registry);
        }
    }
}

最后则是通过上述工厂打开会话,初始化数据库表,然后保存对象实例,如下:

package hibernate;

import hibernate.entity.Student;
import hibernate.util.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.Transaction;

import java.util.List;

public class App {
    public static void main(String[] args) {
Student student
= new Student("Jeffcky1", "Wang1", "[email protected]"); Student student1 = new Student("Jeffcky2", "Wang2", "[email protected]"); Transaction transaction = null; try (Session session = HibernateUtil.getSessionFactory().openSession()) { // start a transaction transaction = session.beginTransaction(); // save the student objects session.save(student); session.save(student1); // commit transaction transaction.commit(); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } try (Session session = HibernateUtil.getSessionFactory().openSession()) { List students = session.createQuery("from Student", Student.class).list(); students.forEach(s -> System.out.println(s.getFirstName())); } catch (Exception e) { if (transaction != null) { transaction.rollback(); } e.printStackTrace(); } } }

 在上述Hibernate配置文件中,我们开启了在控制台输出SQL日志,如下:

Hibernate: create table Student (id integer not null auto_increment, email varchar(255), firstName varchar(255), lastName varchar(255), primary key (id)) engine=MyISAM

总结 

本节我们学习了如何通过Hibernate来创建数据库表的基本过程,我们需要通过JPA注解POJO对象,然后通过配置文件配置数据库连接和映射POJO对象,最后创建Hibernate会话工厂开启管理对象会话。本节我们到此结束,还是比较简单,下一节我们开始讲解命名策略。

你可能感兴趣的:(Hibernate入门之创建数据库表)