1.构造实体类
描述数据库表的结构,表中的字段对应类中的属性,数据库中的表对应一个类。
package com.hibernate;
import java.util.Date;
public class User {
//用户id
private String id;
//用户名称
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
2.构造映射文件User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
<class name="com.hibernate.User" ><!-- table="t_user" -->
<!-- 映射主键 -->
<id name="id">
<!-- 主键生成策略,利用生成器 -->
<generator class="uuid"></generator>
</id>
<!-- 利用property映射其他字段 -->
<property name="name" ></property><!-- 若加上column="user_name",数据库字段名为user_name -->
</class>
</hibernate-mapping>
3.编写核心配置文件hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 驱动类 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 连接的url,数据库名称为hibernate_first -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<!-- 适配器,方言,用于翻译成mysql的语句 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 设置打印到控制台 -->
<property name="hibernate.show_sql">true</property>
<!-- 格式化sql -->
<property name="hibernate.format_sql">true</property>
<!-- 映射文件加入 -->
<mapping resource="com/hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4.编写测试类
编写之前应手动在如mysql等数据库软件中手动创建库,因为hibernate只会自动建表,不会自动建库。
public static void main(String[] args){
Configuration cfg=new
Configuration().configure();
//工具类
SchemaExport export=new SchemaExport(cfg);
//打到控制台,输出到数据库
export.create(true, true);
}
这个方法主要功能是将hbm生成ddl语句,进行建表。DDL是用来操作数据库、表、视图等,所以最终需要转换成ddl语句来完成建表。
<properties>
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
执行之后,控制台输入内容如下:
drop table if exists User
create table User (
id varchar(255) not null,
name varchar(255),
primary key (id)
)