hibernate框架,自己一直在门外徘徊,迟迟进不去。这次hibernate又一次展现了他的魅力。原来hibernate还有将实体代码导出数据表的功能,太神奇了。
需求:
将用户实体,通过hibernate框架导出数据库user表。
Demo
mysql数据库连接:
<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">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="com/zhou/hibernate/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
实体类:
package com.zhou.hibernate;
import java.util.Date;
/**
* User实体类
* Created by zhou on 2017/3/21.
*/
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:
<hibernate-mapping>
<class name="com.zhou.hibernate.User">
<id name="id">
<generator class="uuid"/>
</id>
<property name="name"/>
<property name="password"/>
<property name="createTime"/>
<property name="expireTime"/>
</class>
</hibernate-mapping>
导入方法:
package com.zhou.hibernate;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
/**
* 将hbm生成ddl
* Created by zhou on 2017/3/21.
*/
public class ExportDB {
public static void main (String[] args){
//默认读取hibernate.cfg.xml文件
Configuration cfg = new Configuration().configure();
SchemaExport export = new SchemaExport(cfg);
export.create(true,true);
}
}
点击小蜘蛛出现:
这里hibernate自带的机制会根据属性的数据类型分配合适的字段长度。
效果图
感谢您的宝贵时间···