学习hibernate的书时版本还是3的,发现上面的schemaExport的写法放到eclipse里报错。查了资料才发现hibernate5.x已经改了。特记录一下
1.首先建立持久类
public class User {
private int id;
private String username;
private String password;
public User() {
}
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
2.编辑映射文件
<?xml version='1.0' encoding='utf-8'?>
<!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License:
GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the
lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. -->
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库驱动 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库路径 -->
<property name="connection.url">
jdbc:mysql://localhost:3306/mystudent?useSSL=false&autoReconnect=true </property>
<!-- 数据库用户名 -->
<property name="connection.username">root</property>
<!-- 数据库密码 -->
<property name="connection.password">root</property>
<!-- 数据库自身的语言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 是否显示数据库执行过程中的SQL语句 -->
<property name="show_sql">true</property>
<property name="current_session_context_class">thread</property>
<!-- 加载映射文件 -->
<mapping resource="User.hbm.xml" />
</session-factory>
</hibernate-configuration>
3.User的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-mapping>
<class name="entiy.User" table="User">
<id name="id" >
<generator class="native"/>
</id>
<property name="username" column="username"/>
<property name="password" column="password"/>
</class>
</hibernate-mapping>
4.schemaExport
Configuration config = new Configuration().configure();
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.configure().build();
Metadata metadata = new MetadataSources(serviceRegistry)
.buildMetadata();
SchemaExport schemaExport = new SchemaExport();
schemaExport.create(EnumSet.of(TargetType.DATABASE), metadata);