本案例结合慕课网使用Struts2+Hibernate开发学生信息管理功能中的一个案例,具体章节在第一章第六节生成表结构,有些人如果是Hibernate4版本照着老师讲的应该可以创建表成功,但有些人如果是Hibernate5,既不报错也不出数据表你不妨可以试着我这个案例来写,下面是详细代码
hibernate.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="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8</property>
<property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="entity/Students.hbm.xml"/>
<mapping resource="entity/Users.hbm.xml"/>
</session-factory>
</hibernate-configuration>
很多人写的是<property name="dialect">org.hibernate.dialect.MySQLDialect</property>如果mysql超过5.5我建议按我上面的写
TestStudents.java文件
package entity;
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 TestStudents {
@Test
public void testSchemaExport(){
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
SchemaExport schemaExport = new SchemaExport();
// Hibernate4.x, 可以直接用true参数
schemaExport.create(EnumSet.of(TargetType.DATABASE), metadata);
}
}
最后运行文件Run As-Junit Test 我是可以出表的