使用hibernate自动生成数据库表

使用hibernate自动生成数据库表

使用hibernate自动生成数据库表在hibernate3.2以后有两种方式:

1,使用hbm.xml形式;2,使用注解的形式。

本文介绍第一种方式:

IDE使用的是MyEclipse8.0,数据库使得是mysql5.1,hibernate3.2

1,新建web项目,导入所需的jar包,(此为最关键一步,导入的jar包一定要匹配)。

2,新建实体类User.java

package entity;

public class User {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int 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 User() {
super();
}

}
<wbr>3,User.hbm.xml的编写</wbr>

<?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">
<!--
Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
<class name="entity.User" table="user" catalog="mysong">
<id name="id" type="java.lang.Integer">

<generator class="native" />
</id>
<property name="name" type="java.lang.String">

</property>

<property name="password" type="java.lang.String">

</property>
</class>
</hibernate-mapping>
4,hibernate.cfg.xml

<?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">

<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

<session-factory>
<property name="show_sql">true</property>

<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/mysong</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="myeclipse.connection.profile">com.mysql.jdbc.Driver</property>

<mapping resource="entity/User.hbm.xml" />

</session-factory>


</hibernate-configuration>

5,部署项目,启动tomcat,并打开项目的任何一个页面,此时数据库表已经生成了,赶快查看数据库吧!

你可能感兴趣的:(Hibernate)