1. Hibernate通過實體類與hbm建立表
阿新 • • 發佈:2018-12-09
Hibernate通過實體類與hbm.xml建立表
開始嘗試了很多次,都沒能成功建立表,問題在於
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
or
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
生成的語句不同(見6)
老版本的MySQL使用TYPE而不是ENGINE(例如,TYPE = MYISAM)。MySQL 5.1為向下相容而支援這個語法,但TYPE現在被輕視,而ENGINE是首先的用法。
MySQLDialect ->“type=MyISAM”
MySQL5Dialect->“engine=MyISAM”
應該使用MySQL5Dialect
-
專案結構
-
建立實體類
Student.java
public class Student implements Serializable { private int id; private String name; private int age; ...//getter setter }
-
建立對映
Student.hbm.xml
<?xml version='1.0' encoding='utf-8'?>
-
配置
hibernate.cfg.xml
<hibernate-configuration> <session-factory> <!--配置資料庫連線--> <property name="connection.url">jdbc:mysql://localhost:3306/test</property> <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property> <property name="connection.username">root</property> <property name="connection.password">123</property> <!--顯示sql語句--> <property name="show_sql">true</property> <property name="format_sql">true</property> <!--設定對映--> <mapping resource="learn/hibernate/entity/Student.hbm.xml"/> <!-- DB schema will be updated if needed --> <!-- <property name="hbm2ddl.auto">update</property> --> </session-factory> </hibernate-configuration>
-
測試類
StudentTest.java
public class StudentTest { //測試在資料庫中根據Student類以及Student.hbm.xml建立表 @Test public void createTable(){ ServiceRegistry sr = new StandardServiceRegistryBuilder().configure().build(); Metadata md=new MetadataSources(sr).buildMetadata(); SchemaExport se=new SchemaExport(); se.create(EnumSet.of(TargetType.DATABASE), md); } }
-
控制檯輸出
-
MySQL5Dialect
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
可以成功建立表,語句如下
Hibernate: drop table if exists stu_tab Hibernate: create table stu_tab ( stu_id integer not null auto_increment, stu_name varchar(255), stu_age integer, primary key (stu_id) ) engine=MyISAM
-
MySQLDialect
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
無法建立,語句如下
Hibernate: drop table if exists stu_tab Hibernate: create table stu_tab ( stu_id integer not null auto_increment, stu_name varchar(255), stu_age integer, primary key (stu_id) ) type=MyISAM
-