www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.announce - Entity 1.3.1 released, stable APIs and enhancements.

Entity is an object-relational mapping tool for the D programming 
language. Referring to the design idea of JPA. support PostgreSQL 
/ MySQL / SQLite.



     PostgreSQL 9.0+
     MySQL 5.1+
     SQLite 3.7.11+



     database



import entity;

 Table("user")
class User : Entity
{
      PrimaryKey
      AutoIncrement
     int id;

     string name;
     double money;
     string email;
     bool status;
}

void main()
{
     DatabaseOption options = new 
DatabaseOption("mysql://root:123456 localhost:3306/huntblog?charset=utf-8");
     EntityManagerFactory entityManagerFactory = 
Persistence.createEntityManagerFactory("default", options);
     EntityManager em = entityManagerFactory.createEntityManager();

     // begin transaction
     em.getTransaction().begin();

     // define your database existing row id in here
     int id = 10;

     auto user = em.find!User(id);
     log("User name is: ", user.name);

     // commit transaction
     em.getTransaction().commit();

     em.close();
     entityManagerFactory.close();
}



     auto user = new User();
     user.name = "Brian";
     user.email = "brian huntlabs.cn";
     user.money = 99.9;

     // insert user
     em.persist(user);
     log("User id is: ", user.id);



     int n = em.remove!User(id);
     log("The member of users deleted is: ", n);



     auto user = em.find!User(id);
     log("User name is: ", user.name);
     user.name = "zoujiaqing";
     em.merge!User(user);
     log("The number of users updated is: ", n);



     // create CriteriaBuilder object from em
     CriteriaBuilder builder = em.getCriteriaBuilder();

     CriteriaQuery!User criteriaQuery = builder.createQuery!User;
     Root!User root = criteriaQuery.from();
     Predicate p1 = builder.equal(root.User.id, id);
     TypedQuery!User typedQuery = 
em.createQuery(criteriaQuery.select(root).where(p1));

     auto user =  cast(User)(typedQuery.getSingleResult());

     log("User name is: ", user.name);



     // create CriteriaBuilder object from em
     CriteriaBuilder builder = em.getCriteriaBuilder();

     CriteriaQuery!User criteriaQuery = builder.createQuery!User;
     Root!User root = criteriaQuery.from();

     Predicate p1 = builder.lt(root.User.id, 1000);  // User id is 
less than 1000.
     Predicate p2 = builder.gt(root.User.money, 0);  // User money 
is greater than 0.
     Predicate p3 = builder.like(root.User.name, "z%");  // User 
name prefix is z.

     TypedQuery!User typedQuery = 
em.createQuery(criteriaQuery.select(root).where(builder.and(p1, 
p2), p3));
     User[] users typedQuery.getResultList();

     log("The number of users found is: ", users.length);



http://code.dlang.org/packages/entity
https://github.com/huntlabs/entity
May 04 2018