mybatis from entry to the master (five) sqlSession API usage

mybatis from entry to the master (five) sqlSession API usage

 A Dian Profile

   SqlSession similar mybatis external interface layer, which almost all external api, therefore, learn to use SqlSession understanding mybatis still necessary.

 The corresponding official documents

Two Dian configuration SqlSession environment <environment />

   <Environment /> includes two configurations, transaction management and data sources. Here configured only for learning, the practical application of the transaction is typically referred Spring container, generally used in the data source sophisticated database connection pool, such as druid , HikariCP

    <environments default="development">
        <environment id="development" >
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

 

 

Wed and constructed using the configuration corresponding to SqlSessionFactory

        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        this.sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

 

 

Four Dian use SqlSessionFactory get SqlSession

  Before acquiring SqlSession example, consider the following three things:

    Transactions: I need to use transactions in session or use the automatic submission function (auto-commit) do? (Usually means a lot of databases and / or JDBC drivers no transaction) 
    connection: I need to rely on MyBatis configuration from the data source to obtain it? Or use the configuration to provide their own? 
    Execute the statement: I need MyBatis reuse prepared statements and / or batch updates (including inserts and deletes) do?

 

  4.1) The default method

    @Test
     public  void sqlSessionTest () {
         // the openSession () will open a transaction, it does not automatically submitted
         // retrieves the current configuration Connection instance from Datasource environment
         // transaction isolation levels jdbc default configuration or data source
         / / not reuse prepared statements, each time a new statement processing 
        the try (= the SqlSession SQLSESSION the this .sqlSessionFactory.openSession ();) { 
            UserMapper Mapper = sqlSession.getMapper (. UserMapper class ); 
            the User User = mapper.selectUser (. 1 ); 
            sqlSession.commit (); 
            Assert.assertTrue (user.getUserId () ==. 1 ); 
        } 
    }

 

  4.2) batch execution (custom)

    / * 
    SqlSession openSession () // enabled by default transaction does not automatically submit 
    SqlSession openSession (boolean autoCommit) // set whether custom submit 
    SqlSession openSession (Connection connection) // need to use a custom connection, you can pass parameters, attention Connection settings does not overwrite the same time and method of both autoCommit, because MyBatis will use is in use, set the Connection environmental 
    SqlSession openSession (TransactionIsolationLevel level) // transaction isolation level 
    SqlSession openSession (ExecutorType execType, TransactionIsolationLevel level) 
    SqlSession openSession (ExecutorType execType) 
    the SqlSession the openSession (ExecutorType execType, the autoCommit Boolean) 
    the SqlSession the openSession (ExecutorType execType, Connection Connection) 
    the Configuration the getConfiguration (); 
     
    ExecutorType.SIMPLE: this type of executor does nothing special. It creates a new prepared statement to execute each statement.
    ExecutorType.REUSE: this type of executor will reuse prepared statements.
    ExecutorType.BATCH: This executor will batch all update statements, if executed SELECT among them, to distinguish them in order to ensure legibility behavior if necessary. 
     * / 
    @Test 
    public  void sqlSessionTest2 () { 
        the SqlSession SQLSESSION = null ;
         the try {
             / * 
            batch execution 
            DEBUG [main] - ==> Preparing : insert into user (user_id, user_name, age, country) values (,,??? ?,) 
            DEBUG [main] - ==> the Parameters: 11 (Integer), ttxxxxxx (String), 11 (Integer), null 
            DEBUG [main] - ==> the Parameters: 12 (Integer), ttxxxxx12 (String), 12 (Integer), null 
             * / 
            SQLSESSION = sqlSessionFactory.openSession (ExecutorType.BATCH);
            UserMapper userMapper=sqlSession.getMapper(UserMapper.class);
            
            
            User user=new User();
            user.setUserId(11);
            user.setAge(11);
            user.setUserName("ttxxxxxx");
            userMapper.insertUser(user);
            
            
            user.setUserId(12);
            user.setAge(12);
            user.setUserName("ttxxxxx12");
            userMapper.insertUser(user);
            
            sqlSession.commit();
            
        }catch (Exception e){
            e.printStackTrace();
            if(sqlSession!=null){
                sqlSession.rollback();
            }
        }finally {
            if(sqlSession!=null){
                sqlSession.close();
            }
        }
    }

 

  4.3) with the statement corresponding to the specified method, performing the corresponding sql  

  The original method is more closer to the bottom. Before sqlSession.getMapper (UserMapper. Class ) acquired corresponding mapper example, but using a dynamic proxy, the generated proxy class, which is the use of a method corresponding to the specified method stement, executes the corresponding sql

    / * 
    Method sqlSession execution of the statement 
    noted, statement corresponding to a mapper class name + method name, corresponding to the designation for the sql statement 
    
    <T> T between selectOne (Statement String, Object Parameter) 
    <E> List <E> selectList is (String Statement, Parameter Object) 
    <T> the cursor <T> selectCursor (Statement String, Object Parameter) // returns a cursor, may be deferred retrieval data 
    <K, V> Map <K , V> selectMap (String statement, Object parameter, String MapKey) 
    int INSERT (Statement String, Object Parameter) 
    int Update (Statement String, Object Parameter) 
    int Delete (Statement String, Object Parameter) 
     * / 
    @Test 
    public  void execSqlTest () {
         the try (= the SqlSession SQLSESSION the this.sqlSessionFactory.openSession()){
            
            Cursor<User> userCursor=sqlSession.selectCursor("com.ttx.example.mapper.UserMapper.selectUser", 1); // statement 是 类名+方法名
            
            Iterator<User> iter=userCursor.iterator();
            while (iter.hasNext()){
                User user=iter.next();
                System.out.println(user.getUserId()+" : "+ user.getUserName());
            }
        }
    }

 

  4.4) @SqlProvider written in java sql code

      UserSqlProvider.java

public static String buildSelectUserById(){
        return new SQL(){{
            SELECT("*");
            FROM("user");
            WHERE("user_id = #{userId}");
            ORDER_BY("user_id");
        }}.toString();
    }

 

  UserSqlProviderMapper.java

    @ResultMap("UserMap")
    @SelectProvider(type = UserSqlProvider.class, method = "buildSelectUserById")
    User selectUserById(@Param("userId") int userId);

 

  UserSqlProviderMapper.xml

<? Xml Version = "1.0" encoding = "UTF-8" ?> 
<! DOCTYPE Mapper 
        the PUBLIC "- // mybatis.org//DTD Mapper 3.0 // EN" 
        "http://mybatis.org/dtd/mybatis mapper.dtd--3 " > 
< Mapper namespace =" com.ttx.example.mapper.UserSqlProviderMapper " > 
    
    <-! The resultMap, the mapping results -> 
    < The resultMap ID =" userMap " type =" com.ttx.example .entity.User " > 
        < constructor > </ constructor >   <-! used to reference the configuration parameters can be omitted -> 
        <id column="user_id" property= "the userId" />   <-! results will be represented by the element id identifying properties of the object -> 
        < Result column = "USER_NAME" Property = "the userName" /> 
        < Result column = "Age" Property = "Age" /> 
        < Result column = "Country" Property = "Country" /> 
    </ The resultMap > 

</ Mapper >

 

  Test code

    // 注解 @SelectProvider
    @Test
    public void sqlProviderTest(){
        
        try(SqlSession sqlSession=this.sqlSessionFactory.openSession()){
            UserSqlProviderMapper mapper=sqlSession.getMapper(UserSqlProviderMapper.class);
            User user=mapper.selectUserById(1);
            
            Assert.assertTrue(user.getUserId()==1);
        }
        
    }
    

 

  Note, the SqlSession after use, the need to close the connection, the above code uses the try () {}, will automatically shut down

 

  Click here to view the source code

 

Learning materials:

  Official Documents

 

Guess you like

Origin www.cnblogs.com/timfruit/p/11391887.html