三、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> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">123456</property> <property name="hibernate.dialect">org.hibernate.dialect.MckoiDialect</property> <!-- 与用户表配置文件对应的配置 --> <mapping resource="com/bjpowernode/hibernate/User.hbm.xml"/> </session-factory> </hibernate-configuration> -
四、User.java实体类代码(创建表对应的类对象)
- package com.bjpowernode.hibernate; import java.util.Date; /** * 用户表对应的类 * @author mk * */ public class User { private String id; private String name; private String password; private Date createTime; private Date expireTime; 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; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getExpireTime() { return expireTime; } public void setExpireTime(Date expireTime) { this.expireTime = expireTime; } } -
五、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.bjpowernode.hibernate.User"> <!-- 主键的配置 --> <id name="id"> <generator class="uuid"/> </id> <property name="name"/> <property name="password"/> <property name="createTime"/> <property name="expireTime"/> </class> </hibernate-mapping> -
六、将User.hbm.xml文件,加入到Hibernate.cfg.xml文件中(配置实体类映射配置文件的链接)
七、建立main方法,调用生成对应的表- package com.bjpowernode.hibernate; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; /** * 将hbm生成ddl * @author mk * */ public class ExoprtDB { public static void main(String[] args) { //默认读取hibernate.cfg.xml文件 Configuration cfg = new Configuration().configure(); SchemaExport export = new SchemaExport(cfg); //调用如下方法创建表 export.create(true, true); } } -