Session


Session is an encapsulation of a series of interaction processes with the database triggered by specific business operations in the application. By establishing a temporary channel, it is responsible for the creation and recycling of connection resources with the database, and at the same time provides more Advanced abstract instruction interface call, session-based advantages:

Developers do not need to worry about whether connection resources are released correctly;

Strict coding standards are more conducive to maintenance and understanding;

Better business encapsulation;

  • Session object parameters:

    • Database connection holder (IConnectionHolder) :

      Specify the data source connection used in this session;

    • Session Executor (ISessionExecutor):

      Define this session in the form of an internal class The session returns the result object and provides a reference to the Session instance object;

  • Sample code to open the session:

    // 使用默认数据源开启会话
    User _result = JDBC.get().openSession(new ISessionExecutor<User>() {
        public User execute(ISession session) throws Exception {
            // TODO 此处填写业务逻辑代码
            return session.findFirst(EntitySQL.create(User.class));
        }
    });
    
    // 使用指定的数据源开启会话
    IConnectionHolder _conn = JDBC.get().getConnectionHolder("oracledb");
    // 不需要关心_conn对象的资源释放
    IResultSet<User> _results = JDBC.get().openSession(_conn, new ISessionExecutor<IResultSet<User>>() {
        public IResultSet<User> execute(ISession session) throws Exception {
            // TODO 此处填写业务逻辑代码
            return session.find(EntitySQL.create(User.class));
        }
    });
  • Database operations based on ISession interface:

    The sample code is based on the CRUD (new, query, modify, delete) operations completed around the user (User) data entity to show how Using the ISession object, the data entity is as follows:

        @Entity("user")
        public static class User extends BaseEntity<User, String> {
    
            @Id
            @Property
            private String id;
    
            @Property(name = "user_name")
            private String username;
    
            @Property(name = "pwd")
            private String pwd;
    
            @Property(name = "sex")
            private String sex;
    
            @Property(name = "age")
            private Integer age;
    
            // 忽略Getter和Setter方法
    
            public static class FIELDS {
                public static final String ID = "id";
                public static final String USER_NAME = "username";
                public static final String PWD = "pwd";
                public static final String SEX = "sex";
                public static final String AGE = "age";
            }
            public static final String TABLE_NAME = "user";
        }
    • Insert:

      User _user = new User();
      _user.setId(UUIDUtils.UUID());
      _user.setUsername("suninformation");
      _user.setPwd(DigestUtils.md5Hex("123456"));
      _user.setAge(20);
      _user.setSex("F");
      // 执行数据插入
      session.insert(_user);
      
      // 或者在插入时也可以指定/排除某些字段
      session.insert(_user, Fields.create(User.FIELDS.SEX, User.FIELDS.AGE).excluded(true));
    • Update:

      User _user = new User();
      _user.setId("bc19f5645aa9438089c5e9954e5f1ac5");
      _user.setPwd(DigestUtils.md5Hex("654321"));
      // 更新指定的字段
      session.update(_user, Fields.create(User.FIELDS.PWD));
    • Find:

      • Method 1: Set conditions through data entities (and conditions will be used to connect non-empty attributes), and query all records that meet the conditions;

        User _user = new User();
        _user.setUsername("suninformation");
        _user.setPwd(DigestUtils.md5Hex("123456"));
        // 返回所有字段
        IResultSet<User> _users = session.find(_user);
        // 或者返回指定的字段
        _users = session.find(_user, Fields.create(User.FIELDS.ID, User.FIELDS.AGE));
      • Method 2: Query all records that meet the conditions through custom conditions;

        IResultSet<User> _users = session.find(
                EntitySQL.create(User.class)
                        .field(User.FIELDS.ID)
                        .field(User.FIELDS.SEX), 
                // 设置Order By条件
                Where.create()
                        .orderDesc(User.FIELDS.USER_NAME));
      • ##Method 3: Paging query;

        IResultSet<User> _users = session.find(
                EntitySQL.create(User.class)
                        .field(User.FIELDS.ID)
                        .field(User.FIELDS.SEX),
                Where.create()
                        .orderDesc(User.FIELDS.USER_NAME),
                // 查询第1页,每页10条记录,统计总记录数
                Page.create(1).pageSize(10).count(true));
      • ##Method 4: Only return the first record that meets the conditions (FindFirst);
      • // 查询用户名称和密码都匹配的第一条记录
        User _user = session.findFirst(EntitySQL.create(User.class), 
                Where.create(
                        Cond.create()
                                .eq(User.FIELDS.USER_NAME).param("suninformation")
                                .eq(User.FIELDS.PWD).param(DigestUtils.md5Hex("123456"))));
      Note

      : More query methods will be in the later "Query" chapter Elaborate;

    • Delete:
      • Delete records based on entity primary key:
      • User _user = new User();
        _user.setId("bc19f5645aa9438089c5e9954e5f1ac5");
        //
        session.delete(_user);
        
        //
        session.delete(User.class, "bc19f5645aa9438089c5e9954e5f1ac5");
      • Delete records based on conditions:
      • // 删除年龄小于20岁的用户记录
        session.executeForUpdate(
                SQL.create(
                        Delete.create(User.class).where(
                                Where.create(
                                        Cond.create()
                                                .lt(User.FIELDS.AGE).param(20)))));
      ##Statistics (Count):
    •     // 统计年龄小于20岁的用户记录总数
      
          // 方式一:
          long _count = session.count(User.class, 
                  Where.create(
                          Cond.create()
                                  .lt(User.FIELDS.AGE).param(20)));
      
          // 方式二:
          _count = session.count(
                  SQL.create(
                          Delete.create(User.class).where(
                                  Where.create(
                                          Cond.create()
                                                  .lt(User.FIELDS.AGE).param(20)))));

      Execute update operation (ExecuteForUpdate):
    • This method is used to execute the ISession interface There is no corresponding method encapsulation provided in the SQL statement and the execution operation will cause changes to the database. After executing this method, the number of affected record rows will be returned. For example, the above execution of deleting user records younger than 20 years old:

          int _effectCount =session.executeForUpdate(
                  SQL.create(
                          Delete.create(User.class).where(
                                  Where.create(
                                          Cond.create()
                                                  .lt(User.FIELDS.AGE).param(20)))));

      ##Note
    • : The above operations all support batch operations. Please read the API interface documentation and related source code for specific usage;