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语法支持,包和添加和项目创建如下:
<dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.13</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.4.12.Final</version> </dependency> </dependencies> <build> <sourceDirectory>src/main/java</sourceDirectory> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>8</source> <target>8</target> </configuration> </plugin> </plugins> </build>
接下来我们创建如上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配置文件,如下:
<!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> <!-- JDBC Database connection settings --> <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost:3306/hibernate_db?serverTimezone=UTC</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- Select our SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property> <!-- Echo the SQL to stdout --> <property name="show_sql">true</property> <!-- Set the current session context --> <property name="current_session_context_class">thread</property> <!-- Drop and re-create the database schema on startup --> <property name="hibernate.hbm2ddl.auto">create-drop</property> <!-- dbcp connection pool configuration --> <property name="hibernate.dbcp.initialSize">5</property> <property name="hibernate.dbcp.maxTotal">20</property> <property name="hibernate.dbcp.maxIdle">10</property> <property name="hibernate.dbcp.minIdle">5</property> <property name="hibernate.dbcp.maxWaitMillis">-1</property> <mapping class="hibernate.entity.Student" /> </session-factory> </hibernate-configuration>
接下来我们创建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", "2752154844@qq.com"); Student student1 = new Student("Jeffcky2", "Wang2", "2752154844@qq.com"); 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<Student> 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会话工厂开启管理对象会话。本节我们到此结束,还是比较简单,下一节我们开始讲解命名策略。