您的位置:首页 > 其它

Hibernate_根据配置文件反向生成表格

2012-08-23 21:00 471 查看
MyEclipse可以帮助Hibernate根据数据库中的表格生成配置文件和实体类,可以查看MyEclipse中配置Hibernate一文。

也可以根据编写好的实体类和配置文件,在数据库中创建相应的表格。

具体步骤如下:

1.编写好实体类和配置文件:

Book.java:

public class Book {
//编号
private long id;
//书名
private String name;
//价格
private double price;
//作者
private String author;
  //省略getter和setter
}


Book.hbm.xml:

<hibernate-mapping>
<class name="com.sunflower.tableentity.Book" table="book">
<id name="id" type="long">
<column name="book_id"></column>
<generator class="increment"></generator>
</id>

<property name="name" column="name" type="string"></property>
<property name="price" column="price" type="double"></property>
<property name="author" column="author" type="string"></property>
</class>
</hibernate-mapping>


其中属性的类型和数据库的对应关系,可以查看java类型,Hibernate类型和数据库类型之间的对应关系一文。

hibernate.cfg.xml:

<hibernate-configuration>

<session-factory>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.url">jdbc:mysql://localhost:3306/book</property>
<property name="connection.username">×××××</property>
<property name="connection.password">×××××</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="myeclipse.connection.profile">mysqldriver</property>

<mapping resource="com/sunflower/tableentity/Book.hbm.xml" />
</session-factory>

</hibernate-configuration>


2.编写好解析配置文件和写入数据库的类:

CreateTable.java:

public class CreateTable {
public static void main(String[] args) {
//解析hibernate.cfg.xml配置文件
Configuration conf = new Configuration().configure();
SchemaExport export = new SchemaExport(conf);
//根据配置文件生成表格,第一个参数是否显示建表语句,第二个参数是否生成表格
export.create(true, false);
}
}


生成的SQL语句:

drop table if exists book
create table book (book_id bigint not null, name varchar(255), price double precision, author varchar(255), primary key (book_id))

运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: