persistent.xml hibernate 利用sql script 自定义生成 table 表
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd" version="2.1"> <persistence-unit name="primary"> <provider>org.hibernate.ejb.HibernatePersistence</provider> <exclude-unlisted-classes>false</exclude-unlisted-classes> <properties> <!-- <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/> --> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> <property name="javax.persistence.schema-generation.database.action" value="drop-and-create" /> <property name="javax.persistence.schema-generation.create-source" value="script" /> <property name="javax.persistence.schema-generation.create-script-source" value="file:///e:/create.sql" /> <property name="javax.persistence.schema-generation.drop-source" value="script" /> <property name="javax.persistence.schema-generation.drop-script-source" value="file:///e:/drop.sql" /> <!-- <property name="javax.persistence.sql-load-script-source" value="META-INF/data.sql"/> --> <!-- <property name="javax.persistence.schema-generation.scripts.action" value="drop-and-create"/> <property name="javax.persistence.schema-generation.scripts.create-target" value="./create.sql"/> <property name="javax.persistence.schema-generation.scripts.drop-target" value="./drop.sql"/> --> </properties> </persistence-unit> </persistence>
注意:
sql语句创建的表要和实体bean对应。否则会出错。
create table Seat (id bigint not null auto_increment, booked bit not null, seat_id bigint, zhibin varchar(25), primary key (id)) create table seat_type (id bigint not null auto_increment, description varchar(25) not null, position varchar(255), price integer not null, quantity integer not null, primary key (id)) alter table Seat add constraint FK9pohag9bkh1suwck1bxtr7cys foreign key (seat_id) references seat_type (id)
sql文件可以放在meta-inf里面:
<property name="javax.persistence.sql-load-script-source" value="META-INF/data.sql"/>
真实路径要在:src/main/resources/META-INF/create.sql
./drop.sql是widlfly从哪里运行的当前目录。