Skip to content

Bridje ORM

gilbertovento edited this page Jul 25, 2017 · 17 revisions

Introduction

Bridje ORM is a Hibernate, JPA like Object Relational Mapping framework for Bridje, it can be used with maven from central repository.

    <dependencies>
        ....
        <dependency>
            <groupId>org.bridje</groupId>
            <artifactId>bridje-orm</artifactId>
            <version>${bridje.version}</version>
        </dependency>
        ....
    </dependencies>

Entitys

Bridje ORM use entitys as the mapping concepts of database tables in your code. Entitys has fields that can be mapped to table columns, and relations for mapping foreign keys.

Let's suppose that we have two related tables (users, groups), an user belongs to a group and the groups can have many users. We have to create two entities (Group, User), Then let's look at the code:

First we created Group entity.

@Entity(table = "groups")     //entity for groups table. 
public class Group
{

    @DbObject
    public static Table<Group> TABLE;                   //Identifying the type of the entity that the table is mapped to (Group).

    @DbObject("id")
    public static TableNumberColumn<Group, Integer> ID; //This field represents the name of the java field that corresponds to the injected TableColumn(id), it is a numerical column. 

    @DbObject("name")
    public static TableStringColumn<Group> NAME;        //This field represents the name of the java field that corresponds to the injected TableColumn(name), it is a string column.

    @Key                                                //Identifying primary key
    @Field
    private Long id;

    @Field                                              //Each field is an private attribute of the Group class.
    private String name;

    public Group(Long id, String name)                  //Object Constructor
    {
        this.id = id;
        this.name = name;
    }
    
    public Long getId()
    {
        return id;
    }

    public void setId(Long id)                         //set and get methods for every field or attribute
    {
        this.id = id;
    }

    public String getName()
    {
        return name;
    }

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

Let's see User entity.

@Entity(table = "users")          //entity for users table. 
public class User
{
    @DbObject
    public static Table<User> TABLE;                      //Identifying the type of the entity that the table is mapped to (User).

    @DbObject("id")
    public static TableNumberColumn<User, Long> ID;

    @DbObject("name")
    public static TableStringColumn<User> NAME;

    @DbObject("clasif")
    public static TableColumn<User, Character> CLASIF;
    
    @DbObject("enable")
    public static TableColumn<User, Boolean> ENABLED;

    @DbObject("counts")
    public static TableNumberColumn<User, Byte> COUNTS;
    
    @DbObject("age")
    public static TableNumberColumn<User, Short> AGE;

    @DbObject("mins")
    public static TableNumberColumn<User, Integer> MINS;

    @DbObject("year")
    public static TableNumberColumn<User, Long> YEAR;

    @DbObject("credit")
    public static TableNumberColumn<User, Float> CREDIT;

    @DbObject("money")
    public static TableNumberColumn<User, Double> MONEY;

    @DbObject("birthday")
    public static TableColumn<User, Date> BIRTHDAY;

    @DbObject("updated")
    public static TableColumn<User, java.sql.Date> UPDATED;

    @DbObject("created")
    public static TableColumn<User, Timestamp> CREATED;

    @DbObject("hour")
    public static TableColumn<User, Time> HOUR;
    
    @DbObject("group")                                       //Identifying the field that represents the relation with the User entity.
    public static TableRelationColumn<User, Group> GROUP;     

    @Key
    @Field
    private Long id;

    @Field
    private String name;
    
    @Field
    private Character clasif;
    
    @Field
    private Boolean enable;
    
    @Field
    private Byte counts;
    
    @Field
    private Short age;
    
    @Field
    private Integer mins;
    
    @Field
    private Long year;
    
    @Field
    private Float credit;
    
    @Field
    private Double money;
    
    @Field
    private Date birthday;
    
    @Field
    private java.sql.Date updated;
    
    @Field
    private Timestamp created;

    @Field
    private Time hour;
    
    @Field(column = "id_group")      //The relation is with the entity Group, the foreign key is **id_group**.
    private Group group;             

    /*
     *Constructor
     *set and get methods for every field or attribute
     */
}

EntityContext and CRUD Operations

In order to create, read, update and delete entitys you must have access to an EntityContext, An EntityContext can be created like this using the JDBCService from Bridje JDBC.

    JdbcService jdbc = Ioc.context().find(JdbcService.class);                  //Get the JdbcService instance.
    DataSourceConfig config = new DataSourceConfig();                          //Create a new DataSource configuration object.
    config.setDriver("org.h2.Driver");                                         //Set the JDBC driver for the connection (ex: com.mysql.jdbc.Driver for MySQL server).
    config.setUrl("jdbc:h2:./target/h2testdb");                                //Set the JDBC url connection string (ex: jdbc:mysql://localhost:3306/database).
    config.setUser("sa");                                                      //Set a valid database user with the required privileges on the target database.
    config.setPassword("");                                                    //Set the password.
    DataSource ds = jdbc.createDataSource(config);                             //Create the DataSource, and now we can use the DataSource.
    EntityContext ctx = Ioc.context().find(OrmService.class).createContext(ds);//Access to EntityContext.

You can call the fixTable method to create the necesary tables into the database before you can do any CRUD operation.

    ctx.fixTable(Group.TABLE);
    ctx.fixTable(User.TABLE);

This code will create the specified table if it does not exists, if the table alrready exists in the database the framework will attempt to create any column or index that is missing.

Inserting and updating an entity.

In order to insert an entity you must call the insert method:

    Group group = new Group(2, "admin");
    ctx.insert(group);

Updating an entity:

    Group group = ctx.find(Group.TABLE, 2);
    group.setName("especial admins");
    ctx.update(group);                      //or ctx.update(group, group.getId());

Deleting an entity.

    Group group = ctx.find(Group.TABLE, 2);
    ctx.delete(group);

Inserting relations.

    User user = new User();
    user.setId(Long.MIN_VALUE);
    user.setName("admin");                   //We can save the rest of the attributes.

   /*
    *  Others set methods (for example: user.setBirthday(new Date(1983, 12, 4)), user.setEnable(1), .......)
    */
    Group group = ctx.find(Group.TABLE, 2);
    user.setGroup(group);                   //saving relation. 
    ctx.insert(user);                       //Creating the firt user.

Another way to insert relations:

    User user = new User();
    user.setId(Long.MIN_VALUE);
    user.setName("admin");
	
    Group group = new Group(3, "super admin");  //Insert group
    ctx.insert(group);
	
    user.setGroup(group);                       //Insert relation
    ctx.insert(user);

Querys

Basic query:

User user = ctx.query(User.TABLE).fetchOne();                      //return the first entity returned by the query.

String name =ctx.query(User.TABLE).fetchOne(User.NAME);            //return the value of the name column.

List<User> users =ctx.query(User.TABLE).fetchAll();                //return List of User entity.

List<String> usersname =ctx.query(User.TABLE).fetchAll(User.NAME); //return List of String with the values of the name column.   

List<User> users =ctx.query(User.TABLE).fetchAll(User.TABLE);      //return List of User entity.

Sorted query:

      

List<User> users =ctx.query(User.TABLE).orderBy(User.AGE.asc()).fetchAll();               //return ascending List of User entity given for the age field.

List<User> users =ctx.query(User.TABLE).orderBy(User.AGE.desc()).fetchAll();              //return descending List of User entity given for the age field.

Filtered query:

      
List<User> users =ctx.query(User.TABLE).where(User.NAME.eq("pep")).fetchAll();                      //Return List of User entity where the name field is equal to "pep".
         
List<User> users =ctx.query(User.TABLE).where(User.NAME.ne("pep")).fetchAll();                      //Return List of User entity where the name field is not equal to "pep".
        
List<User> users =ctx.query(User.TABLE).where(User.NAME.like("%pep%")).fetchAll();                  //Return List of User entity where the name field match with regular expression "%pep%".
        
List<User> users =ctx.query(User.TABLE).where(User.NAME.in("pep","pepe")).fetchAll();               //Return List of User entity where the name field is in the list ("pep","pepe").
        
List<User> users =ctx.query(User.TABLE).where(User.NAME.notIn("pep","pepe")).fetchAll();            //Return List of User entity where the name field is not the list ("pep","pepe").
        
List<User> users =ctx.query(User.TABLE).where(User.NAME.isNull()).fetchAll();                       //Return List of User entity where the name field is null.
        
List<User> users =ctx.query(User.TABLE).where(User.NAME.isNotNull()).fetchAll();                    //Return List of User entity where the name field is not null. 

List<User> users =ctx.query(User.TABLE).where(User.NAME.eq("pep").and(User.AGE.gt(35))).fetchAll(); //Return List of User entity where the name field is equal to "pep" and the age field greater than 35.
        
List<User> users =ctx.query(User.TABLE).where(User.NAME.eq("pep").and(User.AGE.ge(35))).fetchAll(); //Return List of User entity where the name field is equal to "pep" and the age field greater than or equal 35.

List<User> users =ctx.query(User.TABLE).where(User.NAME.eq("pep").and(User.AGE.lt(35))).fetchAll(); //Return List of User entity where the name field is equal to "pep" and the age field less than 35.

List<User> users =ctx.query(User.TABLE).where(User.NAME.eq("pep").or(User.AGE.le(35))).fetchAll();  //Return List of User entity where the name field is equal to "pep" or the age field less than or equal 35.

Join query:

You can perform querys like this:

Group group = ctx.query(User.TABLE)
                .orderBy(User.AGE.asc())
                .join(User.GROUP)
                .where(Group.NAME.eq("Admins 2").or(User.NAME.like("%Admin%")))
                .orderBy(Group.NAME.asc())
                .fetchOne();

In this example the User class will be generated at compile time by an annotation processor that the framework provides, with this class you can create conditions, order by statements, and joins, to use in your querys.

Left Join:

Group group = ctx.query(User.TABLE)
                .orderBy(User.AGE.asc())
                .leftJoin(User.GROUP)                                             //apply leftjoin.
                .where(Group.NAME.eq("Admins 2").or(User.NAME.like("%Admin%")))
                .orderBy(Group.NAME.asc())
                .fetchOne();

Rigth Join:

Group group = ctx.query(User.TABLE)
                .orderBy(User.AGE.asc()).
                .rightJoin(User.GROUP)                                            //apply rigthjoin.          
                .where(Group.NAME.eq("Admins 2").or(User.NAME.like("%Admin%")))
                .orderBy(Group.NAME.asc())
                .fetchOne();