我使用 Eclipse Oxygen 作为开发工具,Radhat OpenJDK 作为 Java SE JDK ,数据库 使用 MySQL 5.7。
OpenJDK 在 https://developers.redhat.com/products/openjdk/overview/ 下载。
Hibernate ORM 框架在 http://hibernate.org/orm/releases/5.2/ 下载。
导入位于 hibernate/lib/required 下的 jar 包:
同时导入 MySQL 的 JDBC 驱动 jar 包:
编写核心配置文件 hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!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>
<!--指定数据库 JDBC 驱动 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!--指定数据库 URL -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/yx_two</property>
<!--指定数据库的用户名 -->
<property name="hibernate.connection.username">root</property>
<!--指定数据库的密码 -->
<property name="hibernate.connection.password">949290</property>
<!--指定数据库方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!--在控制台显示执行的数据库操作语句 -->
<property name="hibernate.show_sql">true</property>
<!--在控制台显示执行的数据库操作语句(格式) -->
<property name="hibernate.format_sql">true</property>
<!--hibernate根据实体自动生成数据库表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!--引入映射文件 -->
<mapping resource="User.hbm.xml" />
</session-factory>
</hibernate-configuration>
编写实体类(持久化类)User.java
public class User {
private int userId;
private String username;
private String password;
private String nickname;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
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;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
}
编写映射文件 User.hbm.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="User" table="user" lazy="true">
<!-- 设置主键 -->
<id name="userId" column="userId">
<!-- id生成策略 -->
<generator class="native"/>
</id>
<!-- unique="true"唯一约束 -->
<property name="username" column="username" unique="true"/>
<property name="password" column="password"/>
<property name="nickname" column="nickname"/>
</class>
</hibernate-mapping>