Skip to content
项目

关于

HibernateD is ORM for D language (similar to Hibernate)

数据与分析

这些数字如何统计

实测星标增长

24小时
正在收集历史
7天
正在收集历史
15天
正在收集历史
1个月
正在收集历史

各周期内的星标净变化,周期相互重叠,并非每日新增。缺失的测量保持空白。星标代表关注度,不代表软件质量。

README.md

原文

HibernateD

DUB Package GitHub CI Gitter

HibernateD is ORM for D language (similar to Hibernate)

The project is hosted on github with documentation available on the wiki.

Uses DDBC as an abstraction layer for the underlying database. DDBC currently supports SQLite, MySQL, Postgres, SQL Server, and potentially Oracle.

SQL dialects supported by Hibernated

Currently hiberanted supports:

  • SQLite (requires SQLite v3.7.11 or later)
  • MySQL (tests are run against mysql v5.7)
  • Postgres
  • ClickHouse 23.8 or later (configuration ClickHouse)

But since the underlying DDBC library now has ODBC support some work is underway to also add

  • SQL Server (2017 & 2019)
  • Oracle (due to the size of the docker image for Oracle this may not be tested during CI)

SQLite

The SQLite dialect stores dates and timestamps in TEXT columns, in the form ddbc writes. Since hibernated 0.7 (ddbc 0.15) that is YYYY-MM-DD and YYYY-MM-DD HH:MM:SS, which SQLite's date and time functions understand; before, it was YYYYMMDD and YYYYMMDDTHHMMSS. Old values are still read, but SQLite compares text byte by byte, so queries (where day = :d, ranges, order by, entities keyed by a date) don't match old rows against new values. Convert existing databases once, for each date and timestamp column:

UPDATE t SET d = substr(d, 1, 4) || '-' || substr(d, 5, 2) || '-' || substr(d, 7, 2)
 WHERE d GLOB '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]';
UPDATE t SET dt = substr(dt, 1, 4) || '-' || substr(dt, 5, 2) || '-' || substr(dt, 7, 2) || ' '
               || substr(dt, 10, 2) || ':' || substr(dt, 12, 2) || ':' || substr(dt, 14, 2)
 WHERE dt GLOB '[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]T[0-9][0-9][0-9][0-9][0-9][0-9]';

More on this, including TIME values and columns that ddbc's own users declared differently, is in ddbc's README.

ClickHouse

ClickHouse is an analytics database. The ClickHouseDialect maps entities onto it, with some differences from the other databases:

  • Tables are created with ENGINE = MergeTree, sorted by the primary key (or by the columns of an @EmbeddedId).
  • Updates run as synchronous ALTER TABLE ... UPDATE mutations. They are much more expensive than in an OLTP database: fine for occasional changes, not for update-heavy workloads. Deletes use lightweight DELETE.
  • There are no transactions: Session.beginTransaction() throws HibernatedException. Each statement is applied on its own.
  • Foreign keys and unique constraints are not supported and are left out of the schema.
  • ClickHouse has no auto-increment, so @Generated keys are generated by the client before the insert: time-based unique ids for long/ulong keys, UUIDs for string keys, and max(key) + 1 for narrower integer keys. The last one is only safe when one process writes the table, so prefer long keys. ClickHouse does not check that keys are unique: a duplicate key gives two rows.
  • Dates and times are stored as Date32 and DateTime64(0), from 1900-01-01 to 2299-12-31; values outside that range are rejected. TimeOfDay properties are stored as text (hh:mm:ss), since ClickHouse 23.8 has no time-of-day type.
  • HQL queries run with join_use_nulls = 1, so that a LEFT JOIN without a match gives NULL, as in SQL.

Sample code:

import hibernated.core;
import std.algorithm;


// Annotations of entity classes

class User {
    long id;
    string name;
    Customer customer;
    @ManyToMany // cannot be inferred, requires annotation
        LazyCollection!Role roles;
}

class Customer {
    int id;
    string name;
    // Embedded is inferred from type of Address
    Address address;

    Lazy!AccountType accountType; // ManyToOne inferred

    User[] users; // OneToMany inferred

    this() {
        address = new Address();
    }
}

@Embeddable
class Address {
    string zip;
    string city;
    string streetAddress;
}

class AccountType {
    int id;
    string name;
}

class Role {
    int id;
    string name;
    @ManyToMany // w/o this annotation will be OneToMany by convention
        LazyCollection!User users;
}

int main() {

    // create metadata from annotations
    EntityMetaData schema = new SchemaInfoImpl!(User, Customer, AccountType,
            Address, Role);




    // setup DB connection factory
    version (USE_MYSQL) {
        import ddbc.drivers.mysqlddbc;
        MySQLDriver driver = new MySQLDriver();
        string url = MySQLDriver.generateUrl("localhost", 3306, "test_db");
        string[string] params = MySQLDriver.setUserAndPassword("testuser", "testpasswd");
        Dialect dialect = new MySQLDialect();
    } else {
        import ddbc.drivers.sqliteddbc;
        SQLITEDriver driver = new SQLITEDriver();
        string url = "zzz.db"; // file with DB
        static import std.file;
        if (std.file.exists(url))
            std.file.remove(url); // remove old DB file
        string[string] params;
        Dialect dialect = new SQLiteDialect();
    }
    // each open Session holds one connection: allow up to 10 at once
    // (the default, 1, makes a second Session wait, then fail)
    DataSource ds = new ConnectionPoolDataSourceImpl(driver, url, params, 10);


    // create session factory
    SessionFactory factory = new SessionFactoryImpl(schema, dialect, ds);
    scope(exit) factory.close();

    // Create schema if necessary
    {
        // get connection
        Connection conn = ds.getConnection();
        scope(exit) conn.close();
        // create tables if not exist
        factory.getDBMetaData().updateDBSchema(conn, false, true);
    }

    // Now you can use HibernateD

    // create session
    Session sess = factory.openSession();
    scope(exit) sess.close();

    // use session to access DB

    // read all users using query
    Query q = sess.createQuery("FROM User ORDER BY name");
    User[] list = q.list!User();

    // create sample data
    Role r10 = new Role();
    r10.name = "role10";
    Role r11 = new Role();
    r11.name = "role11";
    Customer c10 = new Customer();
    c10.name = "Customer 10";
    c10.address = new Address();
    c10.address.zip = "12345";
    c10.address.city = "New York";
    c10.address.streetAddress = "Baker st., 12";
    User u10 = new User();
    u10.name = "Alex";
    u10.customer = c10;
    u10.roles = [r10, r11];
    sess.save(r10);
    sess.save(r11);
    sess.save(c10);
    sess.save(u10);

    // load and check data
    User u11 = sess.createQuery("FROM User WHERE name=:Name").
        setParameter("Name", "Alex").uniqueResult!User();
    assert(u11.roles.length == 2);
    assert(u11.roles[0].name == "role10" || u11.roles.get()[0].name == "role11");
    assert(u11.roles[1].name == "role10" || u11.roles.get()[1].name == "role11");
    assert(u11.customer.name == "Customer 10");
    assert(u11.customer.users.length == 1);
    assert(u11.customer.users[0] == u10);
    assert(u11.roles[0].users.length == 1);
    assert(u11.roles[0].users[0] == u10);

    // remove reference
    u11.roles = u11.roles().remove(0);
    sess.update(u11);

    // remove entity
    sess.remove(u11);
    return 0;
}

Additional Features

Cancelling a query

Session.cancelQuery() stops the query the session runs, as in Hibernate. It may be called from another thread or vibe.d task, and does nothing when no query runs. The cancelled call throws ddbc's SQLException with SQLSTATE 57014, and the session stays usable. It uses ddbc's Statement.cancel() (ddbc 0.16), so what it can stop depends on the database: see ddbc's README. With MySQL it throws SQLFeatureNotSupportedException while a statement runs. It doesn't reach the statements of doWork, nor ClickHouse's key lookup on save(). A cancel that comes while the statement is still being prepared may miss it: call it again if the query goes on.

// another thread or task
sess.cancelQuery();

Query timeout

Query.setTimeout(seconds) limits each SQL statement a query runs, as in Hibernate. The limit also covers the queries that load the result's eager relations within the same call (each with the full limit), but not lazy loads later. 0, the default, keeps the connection's own setting. When the limit runs out, the call throws ddbc's SQLTimeoutException (SQLSTATE HYT00; MySQL keeps the server's error), and the session stays usable. It uses ddbc's Statement.setQueryTimeout(), so what counts depends on the database: see ddbc's README. With MySQL, mysql-native drops the session's connection after the timeout's error, so an open transaction is lost.

import ddbc.core : SQLTimeoutException;

try {
    Report[] rows = sess.createQuery("FROM Report").setTimeout(30).list!Report();
} catch (SQLTimeoutException e) {
    // the query took longer than 30 seconds
}

Composite Keys

If a database contains tables with a composite primary key, the @EmbeddedId can be used to represent this. The columns that represent the primary key should be in an @Embeddable class which is then referenced in a property annotated with @EmbeddedId.

For example, consider a database table created via the following SQL command:

CREATE TABLE invoices (
    vendor_no VARCHAR(8) NOT NULL,
    invoice_no VARCHAR(20) NOT NULL,
    amount_e4 INTEGER);
ALTER TABLE invoices
    ADD CONSTRAINT invoices_pkey PRIMARY KEY (vendor_no, invoice_no);

To represent this using HibernateD, the following code would be used:

@Embeddable
class InvoiceId {
    string vendorNo;
    string invoiceNo;

    // Be sure to implement this to benefit from session caching.
    bool opEquals(const InvoiceId o) const @safe {
        return vendorNo == o.vendorNo && invoiceNo == o.invoiceNo;
    }
}

@Table("invoices")
class Invoice {
    @EmbeddedId InvoiceId invoiceId;
    int amountE4;
}

Note: At the time of writing, there are important limitations.

  1. The function DBInfo.updateDbSchema(Connection conn, bool dropTables, bool createTables) does not generate schemas with compound keys.
  2. The Hibernate annotation @JoinColumns (plural) has not yet been implemented, thus, the @ManyToOne and @ManyToMany relations are not usable for classes using an @EmbeddedId.
  3. The @Embedded class referenced via an @EmbeddedId property should implement opEquals in order to gain performance benefits from session caching.
  4. A @ManyToOne or @OneToOne may use one column of the @EmbeddedId as its @JoinColumn, e.g. @ManyToOne @JoinColumn("vendor_no") Vendor vendor;. The key's value is what is stored: a related entity whose key differs from it is ignored when saving. These features will be added in future updates.

探索相关项目

加载中…