1、对与java项目,做数据库迁移时,都会用的数据脚本。
2、当引入hibernate时,可以创建数据库表的配置文件。可以根据表的配置文件自动在数据库建表。(数据库要预先建立好,因为hibernate只会建表,不会建库)
步骤:
1)、在配置文件 hibernate.cfg.cml 中加入参数 ,配置相关数据源参数和pojo文件
- <hibernate-configuration><session-factory>
- <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
4. <property name="connection.username">root</property>
5. <property name="connection.password">mysecretpassword</property>
6. <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
7.
8. < property name="hbm2dll.auto">update</property>
9. <property name="javax.persistence.validation.mode">none</property>
10. <property name="show_sql">true</property>
11.
12. <mapping resource="com/bean/User.hbm.xml"/>
13. <mapping resource="com/bean/Journal.hbm.xml"/>
14. <mapping resource="com/bean/Article.hbm.xml"/>
15. <mapping resource="com/bean/Chapter.hbm.xml"/>
16. <mapping resource="com/bean/Paragraph.hbm.xml"/>
17.</session-factory></hibernate-configuration>
#update 表示自动根据model对象来更新表结构,启动hibernate时会自动检查数据库,如果缺少表,则自动建表;如果表里缺少列,则自动添加列。
#create:启动hibernate时,自动删除原来的表,新建所有的表,所以每次启动后的以前数据都会丢失。
#create-drop:启动hibernate时,自动创建表,程序关闭时,自动把相应的表都删除。所以程序结束时,表和数据也不会再存在。
2)配置pojoname.hbm.xml配置文件,添加hibernate-mapping.
<hibernate-mapping>
- <class name="com.bean.Article" table="article" catalog="test">
- <id name="article_id" type="java.lang.Integer">
- <column name="article_id"></column>
- <generator class="identity"></generator>
- </id>
- <property name="outline" type="java.lang.String">
- <column name="outline" length="20" not-null="false"></column>
- </property>
- <property name="title" type="java.lang.String">
- <column name="title" length="20" not-null="false"></column>
- </property>
- <many-to-one name="journal" class="com.bean.Journal"
- column="journal_id" not-null="true" cascade="all"></many-to-one>
- <set name="chapters" inverse="true" cascade="all">
- <key column="article_id"></key>
- <one-to-many class="com.bean.Chapter"></one-to-many>
- </set>
- </class>
- </hibernate-mapping>
3、建立一个启动类
public class InportDatabase {
-
- public static void main(String[] args) {
- Configuration cfg = new Configuration().configure();
- SchemaExport export = new SchemaExport(cfg);
- export.create(true, true);
- }
- }
即可根据配置文件在数据库中建立相应的表。