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


    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:

     1 <hibernate-mapping>
     2     <class name="com.sunflower.tableentity.Book" table="book">
     3         <id name="id" type="long">
     4             <column name="book_id"></column>
     5             <generator class="increment"></generator>
     6         </id>
     7 
     8         <property name="name" column="name" type="string"></property>
     9         <property name="price" column="price" type="double"></property>
    10         <property name="author" column="author" type="string"></property>
    11     </class>
    12 </hibernate-mapping>

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

    hibernate.cfg.xml:

     1 <hibernate-configuration>
     2 
     3     <session-factory>
     4         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
     5         <property name="connection.url">jdbc:mysql://localhost:3306/book</property>
     6         <property name="connection.username">×××××</property>
     7         <property name="connection.password">×××××</property>
     8         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
     9         <property name="myeclipse.connection.profile">mysqldriver</property>
    10 
    11         <mapping resource="com/sunflower/tableentity/Book.hbm.xml" />
    12     </session-factory>
    13 
    14 </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))

    运行结果:

     

  • 相关阅读:
    C# 读取本地图片 转存到其他盘符
    Sql server之路 (六)上传服务器图片
    wp8 ListPicker
    Sql server之路 (五)插入多条数据
    Wcf for wp8 调试Wcf服务程序(四)
    win8 鼠标失灵解决办法
    Sql server之路 (一)基础学习
    Caché开发环境介绍
    Cache数据库简介
    MYSQL之sql优化——慢查询日志
  • 原文地址:https://www.cnblogs.com/hanyuan/p/2653251.html
Copyright © 2020-2023  润新知