Hibernate自动生成数据库中的表
程序员文章站
2024-03-21 23:06:34
...
在第一个Hibernate项目的基础上,创建了一个Goods实体类,并定义三个属性id,name,price。
package demo1;
public class Goods {
private int id;
private String name;
private int price;
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 int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
创建该实体类的映射文件Goods.hbm.xml
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping >
<class name="demo1.Goods" table="t_Good">
<id name="id" type="int">
<generator class="identity"/>
</id>
<property name="name" type="string"/>
<property name="price" type="int"/>
</class>
</hibernate-mapping>
在Hibernate.cfg.xml中添加生成表的语句,这里我用的是update,好处在于如果有表就创建,没表就不创建。create-drop则是在执行SessionFactory时创建表,调用close方法时删除表。
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!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>
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/mysql</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping resource="demo1/User.hbm.xml"/>
<mapping resource="demo1/Goods.hbm.xml"/>
</session-factory>
</hibernate-configuration>
最后在mysql中查询建的表,因为没有数据,所以显示为空
上一篇: 【面试题】基础篇02
下一篇: day4课堂笔记