mybatis -------- Getting a case study notes

first step:

  Import dependence

<dependencies>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.5.4</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId></slf4j-APIartifactId>
        <version>1.7.30</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>compile</scope>
    </dependency>

 

Step Two: Configure core file --SqlMapConfig.xml

<? Xml Version = "1.0" encoding = "UTF-8" ?> 
<! DOCTYPE the Configuration 
        the PUBLIC "- // mybatis.org//DTD Config 3.0 // EN" 
        "http://mybatis.org/dtd/mybatis config.dtd--3 " > 


<-! MyBatis basic profile: a main configuration basic context parameters and operating environment -> 
< configuration > 

    <-! configuration -> 
    < Properties Resource =" dbconfig.properties " > </ Properties > 
    <-! settings -> 
    < settings > 
        <-! global cache configuration of the switching: If there is provided false, then even in the open configuration mapper does not help ->
        <setting name- Allow JDBC Primary key generation, need to drive compatibility. If set to true, then this setting forces used to automatically generate the primary key, some drivers may not be compatible but still work -> < Setting name 
        
         
        
         
        
         
        
        = "useGeneratedKeys" value = "to false"  /> 
        <-! Specifies MyBatis how to automatically map columns fields or properties: NONE indicates automatic mapping canceled; represents only the PARTIAL automatic mapping, and does not define a mapping result nested results set ; FULL automatically mapped arbitrarily complex set of results, whether the nested -> 
        < Setting name = "autoMappingBehavior" value = "the PARTIAL"  /> 
        <-! configure the default effector: SIMPLE ordinary actuator; the REUSE reuses prepared statements; bATCH reuse the statement and perform bulk updating -> 
        < setting name = "defaultExecutorType" value = "the SIMPLE"  /> 
        <-! timeout setting: it determines the number of seconds in response to the drive waits for the database, any positive integer -> 
        < Setting name = "defaultStatementTimeout" value="25"/>
        <!--Article Set default database driver return limit, this parameter can be reset, any positive integer -> 
        < Setting name = "defaultFetchSize" value = "100"  /> 
        <-! Allowed in a nested statements tab ( RowBounds) -> 
        < Setting name = "safeRowBoundsEnabled" value = "to false"  /> 
        <-! is turned on automatically hump naming rules, i.e. mapping from a_example to aExample -> 
        < Setting name = "mapUnderscoreToCamelCase" value = " to true "  /> 
        <-! local cache mechanisms to prevent the circular reference acceleration and repeating nested loops -> 
        < Setting name =" localCacheScope " value="SESSION" />
        <! - when no specific JDBC type parameter specifies the JDBC type is null. Some drivers need to specify the JDBC type column, in most cases directly to a general type, such as NULL / VARCHAR / OTHER -> 
        < Setting name = "jdbcTypeForNull" value = "OTHER"  /> 
        <-! Specified trigger delay loading methods, such as the equals / clone / the hashCode / toString -> 
        < Setting name = "lazyLoadTriggerMethods" value = "the equals"  /> 
    </ Settings > 


    <-! alias: aliases pojo object -> 
    < typeAliases > 
        <! - class separately alias   -> 
        < typeAlias alias = "User"> </ TypeAlias > 
        ! <- packet scan batches alias setting, setting rule is: Get the name of the class, which is the first letter lowercase -> 
    <-!         <Package name = "COM .itheima.domain "/> -> 
    </ typeAliases > 


    <-!    configuration environment -> 
    < environments default =" mysql " > 

        <-! environment configuration of mysql -> 
        < environment ID =" mysql " > 
            <-! type configuration affairs -> 
            < transactionManager of the type = "JDBC" > </ transactionManager > 
            <!- Configure Connection Pool -> 
            <dataSource type="POOLED">
                <!--配置连接数据库的4个基本信息-->
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <! - Specifies the location mapping configuration file, a mapping configuration file refers to each separate profiles dao -> 
    < by mappers > 
      <! - <Resource Mapper = "COM / itheima / Mapper / IUserMapper.xml" / > ->   
        < package name = "com.itheima.mapper" /> 
    <-! here in the form of a bonded interface, then using the package path mapping, the mapping should be noted that the interface belonging to the same file path - ->
</ by mappers > </ Configuration >

The third step: configuration mapping file

  

<? 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 " > 

! <- 
namespace: namespace; full class name specified interface 
id: uniquely identifies 
resultType: return value type 
# {id}: id taken from the parameter value of the passed 
 -> 
< Mapper namespace = "com.itheima.mapper.IUserMapper" > 
    < SELECT ID = "the findAll" the resultType = "User" > 
       SELECT * from User; 
    </ SELECT > 

    <insert id="add" parameterType="com.itheima.domain.User">
        insert into user (id,username) values (#{id},#{username});
    </insert>

    <update id="update" parameterType="com.itheima.domain.User">
        update user set username=#{username} where id=#{id}
    </update>


    <delete id="del" parameterType="int">
        delete from user where id=#{id}
    </delete>
</mapper>

 

Step Four: Test

  

package com.itheima.test;

import com.itheima.domain.User;
import com.itheima.mapper.IUserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest {

@Test
    public void test() throws{IOException
         // read the core profile stream object generating 
        the InputStream Resources.getResourceAsStream IS = ( "the SqlMapConfig.xml" );
         // Builder mode 
        the SqlSessionFactoryBuilder SqlSessionFactoryBuilder = new new the SqlSessionFactoryBuilder ();
         // Create SqlSession plant 
        a SqlSessionFactory SqlSessionFactory = the sqlSessionFactoryBuilder.build (IS); 
        SqlSession SQLSESSION = sqlSessionFactory.openSession (); 
        IUserMapper UserMapper = sqlSession.getMapper (IUserMapper. class ); 

  // query all 
       List <the User> = the Users userMapper.findAll ();
        for (User user:users) {
            System.out.println(user);
        }

  /*     //添加
    User user = new User();
    user.setId(2);
    user.setUsername("zhangsan");

  userMapper.add(user);

*/
 /* User user=new User(); user.setId(2); 
user.setUsername("wangwu");
userMapper.update(user);
*/

/*userMapper.del(2);*/
sqlSession.commit(); sqlSession.close(); } }

 

Guess you like

Origin www.cnblogs.com/liudingwei/p/12649988.html