在使用<property name="hibernate.hbm2ddl.auto" value="create" /> 这个语句自动建表屡试无果后我决定学习另一种看起来比较麻烦的方法来进行自动建表!
配置好的实体类、xxx.hbm.xml文件和xxx.cfg.xml文件需要做的变动不多,只要有下面几处:
xxx.cfg.xml文件中:
<!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>
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle9iDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">123456</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<mapping resource="org/User/hibernate.hbm.xml"/>
</session-factory>
</hibernate-configuration>
基本是不变的,需要注意的是要自动建表的数据库名要确定,学习的过程中参考网上的资料中有一句
- <!-- 格式化sql -->
- <property name="hibernate.format_sql">true</property>
因为感觉格式化会删除掉以前建的表,就没加上,并没有影响最后的结果,哈哈哈。
xxx.hbm.xml文件中表明和主键的生成策略要改动一下:
<hibernate-mapping>
<class name="org.User.User" table="C_USER">
<id name="id" type = "int">
<!-- 主键生成策略,利用生成器 -->
<generator class="uuid"></generator>
</id>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="password" type="java.lang.String">
<column name="PASSWORD" />
</property>
<property name="age" type="int">
<column name="AGE" />
</property>
<property name="gender" type="java.lang.String">
<column name="Gender" />
</property>
</class>
</hibernate-mapping>
最后编写测试文件,在src目录下新建TestC_user:
最初找到的代码是这样的:
- public static void main(String[] args){
- //读取的是properties文件
- //Configuration cfg=new Configuration();
- Configuration cfg=new Configuration().configure();
- //工具类
- SchemaExport export=new SchemaExport(cfg);
- //打到控制台,输出到数据库
- export.create(true, true);
- }
按照这个编写测试类之后在第七行的参数上面总是报错,后来发现这已经是过时的代码了,在网上找到适合hibernate 5.2.10的代码:
package org.Test;
import java.util.EnumSet;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
import org.junit.Test;
public class TestC_user {
@Test
public void test() {
ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().configure().build();
Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
SchemaExport schemaExport = new SchemaExport();
schemaExport.create(EnumSet.of(TargetType.DATABASE), metadata);
}
}
进行测试,测试成功后结果如下图:
自动创建的C_USER:
因为没有添加数据,此时的C_USER表中没有任何内容: