如何程序化的构造Hibernate配置 // How to initialize Hibernate programmably

Java为什么被人诟病,因为一切都是过度设计。Hibernate其实就是实现了一套JPA的ORM,不过用极度冗赘的配置方式,nodejs Sequelize.js,甚至Python SQLAlchemy,都比Java的实现优雅的多。当然这个是历史问题了,就没必要抱怨了。

许多时候,我们不需要用hibernate.cfg.xml,并没有程序化的简单可控。

下面开始实战。

假设使用了Maven系统,首先确认hibernate-core已经作为依赖添加到pom.xml。

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.16.Final</version>
        </dependency>

下面添加一个User类作为范例。

package com.jcube.mies.admin;

import java.util.UUID;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "User")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", unique = true, nullable = false)
    private Long id;

    @Column(name = "uuid", length = 32, unique = true, nullable = false)
    private UUID uuid;

    @Column(name = "name", length = 32, unique = true, nullable = false)
    private String name;

    public User() {
        uuid = UUID.randomUUID();
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public UUID getUuid() {
        return uuid;
    }

    public void setUuid(UUID uuid) {
        this.uuid = uuid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

对于Annoataion的用法,可以参考JPA和Hibernate的文档。

这里用于示范的User类有3个成员变量,分别是id,这个是数据库的主键;然后还有个uuid,使用的是Java的UUID类型,全局唯一标示符;还有个name,一个字符串,代表名字。

其实通过这个类,已经足够让Hibernate生成数据表了。

下面程序化的构造SessionFactory,这个算是Hibernate的基本API接口。

package com.sample;

public class Launcher {

    private static SessionFactory sessionFactory = null;

    public static void main(String[] args) {

        // Create the session factory.
        try {
            Configuration cfg = new Configuration();
            cfg.setProperty("hibernate.show_sql", "true");
            cfg.setProperty("hibernate.format_sql", "true");
            cfg.setProperty("hibernate.use_sql_comments", "true");
            cfg.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
            cfg.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
            cfg.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/testdb");
            cfg.setProperty("hibernate.connection.username", "testuser");
            cfg.setProperty("hibernate.connection.password", "testpwd");
            cfg.setProperty("hibernate.hbm2ddl.auto", "create");
cfg.addAnnotatedClass(User.
class); StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()); sessionFactory = cfg.buildSessionFactory(builder.build()); } catch (Exception e) { e.printStackTrace(); System.exit(1); } }

一堆的setProperty()配置。

hibernate.show_sql,
hibernate.format_sql
use_sql_comments

这里设置为true,用户调试输出。

然后用户配置数据库,包括地址,用户名密码等等。

最后直接调用addAnnotatedClass(),用来直接告诉Hibernate配置,我们需要映射这个类。

完毕。

posted on 2018-04-08 17:34  Bo Schwarzstein  阅读(294)  评论(0编辑  收藏  举报