hibernate学习记录,如何将写成的类映射成数据库表!

来源:互联网 发布:股票交易记录分析软件 编辑:程序博客网 时间:2024/06/18 05:32

之前学过一阵子的python,Django。里边的model就是类似于hibernate的一种ORM模型,写起来貌似很方便,而且操作数据库更加简洁!

在IDEA中,可以轻而易举的将mysql中的数据表映射成实体和单独的类,有的时候对这种自带的实体并不满意,自己来写实体,这个时候就想,能不能把实体映射到数据库中的表中!java是如何做到的呢?在网上搜索了一阵子,据说是写好配置文件,在hibernate中添加一个update元素,然后运行整个程序就好了,不幸的是,我并没有成功!于是搜索其他方法:通过一运行一个java来实现,成功了...

import org.hibernate.boot.Metadata;import org.hibernate.boot.MetadataSources;import org.hibernate.boot.registry.StandardServiceRegistry;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;import org.hibernate.tool.hbm2ddl.SchemaExport;import org.hibernate.tool.schema.TargetType;import java.util.EnumSet;public class exportDB {    /**     * 将hbm转成ddl     *     * @param args     */    public static void main(String[] args) {//        // 如果直接new Configuration 默认读取的是hibernate.properties 文件//        // 后边再加.configure()读取的才是hibernate.cfg.xml 文件,//        Configuration cfg = new Configuration().configure();//        // 创建SchemaExport对象//        SchemaExport export = new SchemaExport(cfg);//        // 生成ddl文件,并在控制台输出//        export.create(true, true);        Configuration config = new Configuration().configure();        StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()                .configure().build();        Metadata metadata = new MetadataSources(serviceRegistry)                .buildMetadata();        SchemaExport schemaExport = new SchemaExport();        schemaExport.create(EnumSet.of(TargetType.DATABASE), metadata);    }}
需要注意的是,其中屏蔽的内容是好多教程上写的,但是Hibernate5.x以后貌似就会报错,这个SchemaExport,她变心了,变得我们不认识了,下边的那种方法才通过编译!,运行后,在hibernate中注册的类才可以映射到数据库中,别忘了数据库得建好,表就不用建了,还有一些已经解决的问题,最近也会更新,欢迎大家私信哦....


阅读全文
1 0