MyBatis simple CRUD and configuration parsing

MyBatis

1、CURD

1、namespace

mapper.xml following package names must match the namespace corresponding to the package name mapper interface!

2、select

Alternatively, the query:

  • id: Method name corresponds to the namespace
  • Method of parameter types: parameterType
  • resultType: After the implementation of the return value sql
  1. The method of adding the corresponding interfaces

    //根据ID查询用户
    User getUserById(int id);
    
  2. Written correspondence mapper.xml inside sql statement

    <select id="getUserById" parameterType="int" resultType="com.jiutong.pojo.User">
            select * from myBatis.user where id = #{id}
    </select>
    
  3. test

    @Test
    public void getUserById(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
        User userById = mapper.getUserById(1);
    
        System.out.println(userById);
        sqlSession.close();
    }
    

3、insert

  1. The method of adding the corresponding interfaces

        //inset用户
        int addUser(User user);
    
  2. Written correspondence mapper.xml inside sql statement

        <!--连接了数据库后,myBatis.user()可以直接得到里面的字段-->
        <!--对象中的属性可以直接取出来-->
        <insert id="addUser" parameterType="com.jiutong.pojo.User">
            insert into myBatis.user(id, name, pwd) values (#{id},#{name},#{pwd})
        </insert>
    
  3. test

        //增删改需要提交事务
        @Test
        public void addUser(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
            mapper.addUser(new User(4,"码字","123456"));
    
            //提交事务
            sqlSession.commit();
            sqlSession.close();
        }
    

4、update

  1. The method of adding the corresponding interfaces

        //修改用户
        int updateUser(User user);
    
  2. Written correspondence mapper.xml inside sql statement

        <!-- 使用 upd 可以快速生成-->
        <update id="updateUser" parameterType="com.jiutong.pojo.User">
            update myBatis.user set name = #{name},pwd=#{pwd} where id=#{id};
        </update>
    
  3. test

        @Test
        public void updateUser(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
            mapper.updateUser(new User(4,"赫赫","654321"));
    
            //提交事务
            sqlSession.commit();
            sqlSession.close();
        }
    

5、delete

  1. The method of adding the corresponding interfaces

        //删除用户
        int deleteUser(int id);
    
  2. Written correspondence mapper.xml inside sql statement

        <delete id="deleteUser" parameterType="int">
            delete from myBatis.user where id = #{id}
        </delete>
    
  3. test

        @Test
        public void deleteUser(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
            mapper.deleteUser(4);
    
            //提交事务
            sqlSession.commit();
            sqlSession.close();
        }
    

6, possible problems

Caused by: org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### The error may exist in com/jiutong/dao/UserMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: org.apache.ibatis.builder.BuilderException: Error creating document instance.  Cause: com.sun.org.apache.xerces.internal.impl.io.MalformedByteSequenceException: 1 字节的 UTF-8 序列的字节 1 无效。

There is garbage problem in the XML file output

target / classes / com / jiutong / dao / UserMapper.xml below

Solution:

  1. ** (not recommended) ** inside the Mapper.Xml <?xml version="1.0" encoding="UTF-8" ?>modified<?xml version="1.0" encoding="UTF8" ?>
  2. ** (recommended) ** open set (Settiongs) - Text encoding (File Encofings) the Project Encoding modified to UTF-8. After modification and deletion target file to re-test

7, to handle insert with Map

  1. The method of adding the corresponding interfaces

        //Map对象
        //通过map对象插入一个User
        int addUserByMap(Map<String,Object> map);
    
  2. Written correspondence mapper.xml inside sql statement

        <insert id="addUserByMap" parameterType="map">
            insert into myBatis.user(id, name, pwd) values (#{mapid},#{mapname},#{mappwd})
        </insert>
    
  3. test

        //通过map来处理
        @Test
        public void addUserByMap(){
            SqlSession sqlSession = MybatisUtils.getSqlSession();
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    
            Map<String,Object> map=new HashMap<String, Object>();
            map.put("mapid",5);
            map.put("mapname","map");
            map.put("mappwd","567");
            mapper.addUserByMap(map);
    
            //提交事务
            sqlSession.commit();
            sqlSession.close();
        }
    

2, configuration parsing

2.1, the core configuration file

  • Official name: mybatis-config.xml

  • MyBatis configuration file contains settings and properties that can deeply affect MyBatis behavior. Top-level configuration document is structured as follows:

    configuration(配置)
        properties(属性)
        settings(设置)
        typeAliases(类型别名)
        typeHandlers(类型处理器)
        objectFactory(对象工厂)
        plugins(插件)
        environments(环境配置)
    		environment(环境变量)
                transactionManager(事务管理器)
                dataSource(数据源)
    databaseIdProvider(数据库厂商标识)
    mappers(映射器)
    

2.2 environment configuration (environments)

Mybatis can be configured to accommodate a variety of environments

But remember: Although you can configure multiple environments, but can choose only one instance of each SqlSessionFactory environment.

Configuring multiple sets of operating environment

Mybatis default transaction manager is JDBC, connection pool POOLED

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--configuration核心配置文件-->
<configuration>
    <!--环境,default为默认环境-->
    <environments default="development">

        <!--第一套环境-->
        <environment id="development">
            <!--在 MyBatis 中有两种类型的事务管理器(也就是 type="[JDBC|MANAGED]")-->
            <transactionManager type="JDBC"/>
            <!--有三种内建的数据源类型(也就是 type="[UNPOOLED|POOLED|JNDI]"):-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.4.108:3306/myBatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>

        <!--第二套环境-->
        <environment id="test">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://192.168.4.108:3306/myBatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>

    </environments>
    <mappers>
        <mapper resource="com/jiutong/dao/UserMapper.xml"/>
    </mappers>
</configuration>

2.3, properties (properties)

We can attribute properties to achieve the reference profile

These properties may be arranged outside, and can be replaced dynamically. You can either configure these properties in a typical Java properties file, you can also set up sub-elements of the properties element.

  • Writing a database configuration file [db.properties] // and mybatis-config.xml sibling

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://192.168.4.108:3306/myBatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
    username=root
    password=root
    
  • Modify mybatis-config.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <!--configuration核心配置文件-->
    <configuration>
        <!--引入外部配置文件-->
        <properties resource="db.properties"/>
        
        <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>
        <mappers>
            <mapper resource="com/jiutong/dao/UserMapper.xml"/>
        </mappers>
    </configuration>
    
    • You can import external files directly

    • In which you can add some attribute configuration

      <properties resource="db.properties">
        <property name="username" value="dev_user"/>
        <property name="password" value="F2Fa3!33TYyg"/>
      </properties>
      
    • If the two files have the same field, external read priority
      such as an external file username=root, and the internal <property name="username" value="dev_user"/>priority read root

    • db.properties the escape character &amp;may be directly written&

    • In addition, as the order of each configuration strict control structure propertiesmust be in a first position

2.4, the type of alias (typeAliases)

  • Type an alias name can be abbreviated to a Java type setting.
  • It is only for XML configuration intended to reduce the redundancy write fully qualified class name.
	<!--可以给实体类起一个别名-->
	<typeAliases>
        <typeAlias type="com.jiutong.pojo.User" alias="User"/>
	</typeAliases>

You can also specify a package name, MyBatis will search package name below the required Java Bean, such as:

** In the absence of annotations, use the first letter lowercase Bean non-qualified class name as an alias for it. ** I found that is not the case, as long as the same letter can be identified

    <!--扫描一个包下面的pojo-->
    <typeAliases>
        <package name="com.jiutong.pojo"/>
    </typeAliases>

In less physical analogy, when using the first.

If the entity classes very much, it is recommended to use the second.

The first can DIY to the alias, the second can be achieved using annotations DIY.

Here are some common Java types for the built-in type aliases.

Aliases Type mappings
_byte byte
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
object Object
map Map
hashmap HashMap
list List
arraylist ArrayList
collection Collection
iterator Iterator

Can be seen all basic types of aliases are _XXX

2.5, provided (Settings)

It is extremely important to adjust the settings MyBatis, they will change the runtime behavior of MyBatis. The table below describes the meaning of each setting of the setting, the default value or the like.

Setting name description Valid values Defaults
cacheEnabled Globally turn on or off any cache configuration file for all configured mapper. true | false true
lazyLoadingEnabled Delay global switch loaded. When turned on, all associations will be delayed loading. In particular by setting the relationship fetchTypeto cover the switching state properties. true | false false
aggressiveLazyLoading All the open, any invocation of a method of loading the object's attributes delay loading. Otherwise, each delay loaded property loaded on demand (reference lazyLoadTriggerMethods). true | false false (default is true in 3.4.1 and earlier versions)
multipleResultSetsEnabled Whether to allow a single statement return multiple result sets (requires a database driver support). true | false true
useColumnLabel Use the column label instead of the column name. The actual performance of the database depends on the driver, specifically refer to the documentation database-driven, or observed by comparative tests. true | false true
useGeneratedKeys JDBC support allows automatic generation of primary keys, needs to support database-driven. If set to true, it will force the use of auto-generated primary key. Although some database driver does not support this feature, but it can still work (eg Derby). true | false False
autoMappingBehavior MyBatis specifies how to automatically map columns fields or properties. Close NONE indicates automatic mapping; the PARTIAL will not automatically mapped field definition nested result mapping. FULL automatically map any complex set of results (whether or not nested). NONE, PARTIAL, FULL PARTIAL
autoMappingUnknownColumnBehavior 指定发现自动映射目标未知列(或未知属性类型)的行为。NONE: 不做任何反应WARNING: 输出警告日志('org.apache.ibatis.session.AutoMappingUnknownColumnBehavior' 的日志等级必须设置为 WARNFAILING: 映射失败 (抛出 SqlSessionException) NONE, WARNING, FAILING NONE
defaultExecutorType 配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(PreparedStatement); BATCH 执行器不仅重用语句还会执行批量更新。 SIMPLE REUSE BATCH SIMPLE
defaultStatementTimeout 设置超时时间,它决定数据库驱动等待数据库响应的秒数。 任意正整数 未设置 (null)
defaultFetchSize 为驱动的结果集获取数量(fetchSize)设置一个建议值。此参数只可以在查询设置中被覆盖。 任意正整数 未设置 (null)
defaultResultSetType 指定语句默认的滚动策略。(新增于 3.5.2) FORWARD_ONLY | SCROLL_SENSITIVE | SCROLL_INSENSITIVE | DEFAULT(等同于未设置) 未设置 (null)
safeRowBoundsEnabled 是否允许在嵌套语句中使用分页(RowBounds)。如果允许使用则设置为 false。 true | false False
safeResultHandlerEnabled 是否允许在嵌套语句中使用结果处理器(ResultHandler)。如果允许使用则设置为 false。 true | false True
mapUnderscoreToCamelCase 是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。 true | false False
localCacheScope MyBatis 利用本地缓存机制(Local Cache)防止循环引用和加速重复的嵌套查询。 默认值为 SESSION,会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地缓存将仅用于执行语句,对相同 SqlSession 的不同查询将不会进行缓存。 SESSION | STATEMENT SESSION
jdbcTypeForNull 当没有为参数指定特定的 JDBC 类型时,空值的默认 JDBC 类型。 某些数据库驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。 JdbcType 常量,常用值:NULL、VARCHAR 或 OTHER。 OTHER
lazyLoadTriggerMethods 指定对象的哪些方法触发一次延迟加载。 用逗号分隔的方法列表。 equals,clone,hashCode,toString
defaultScriptingLanguage 指定动态 SQL 生成使用的默认脚本语言。 一个类型别名或全限定类名。 org.apache.ibatis.scripting.xmltags.XMLLanguageDriver
defaultEnumTypeHandler 指定 Enum 使用的默认 TypeHandler 。(新增于 3.4.5) 一个类型别名或全限定类名。 org.apache.ibatis.type.EnumTypeHandler
callSettersOnNulls 指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这在依赖于 Map.keySet() 或 null 值进行初始化时比较有用。注意基本类型(int、boolean 等)是不能设置成 null 的。 true | false false
returnInstanceForEmptyRow 当返回行的所有列都是空时,MyBatis默认返回 null。 当开启这个设置时,MyBatis会返回一个空实例。 请注意,它也适用于嵌套的结果集(如集合或关联)。(新增于 3.4.2) true | false false
logPrefix 指定 MyBatis 增加到日志名称的前缀。 任何字符串 未设置
logImpl 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。 SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING 未设置
proxyFactory 指定 Mybatis 创建可延迟加载对象所用到的代理工具。 CGLIB | JAVASSIST JAVASSIST (MyBatis 3.3 以上)
vfsImpl 指定 VFS 的实现 自定义 VFS 的实现的类全限定名,以逗号分隔。 未设置
useActualParamName 允许使用方法签名中的名称作为语句参数名称。 为了使用该特性,你的项目必须采用 Java 8 编译,并且加上 -parameters 选项。(新增于 3.4.1) true | false true
configurationFactory 指定一个提供 Configuration 实例的类。 这个被返回的 Configuration 实例用来加载被反序列化对象的延迟加载属性值。 这个类必须包含一个签名为static Configuration getConfiguration() 的方法。(新增于 3.2.3) 一个类型别名或完全限定类名。 未设置

2.6、其他配置

2.7、映射器(mappers)

方法一:使用相对于类路径的资源引用

<mappers>
    <mapper resource="com/jiutong/dao/UserMapper.xml"/>
</mappers>

方法二:使用映射器接口实现类的完全限定类名

<mappers>
  <mapper class="com.jiutong.dao.UserMapper"/>
</mappers>

注意点:

  • 接口和它的Mapper配置文件必须同名
  • 接口和它的Mapper配置文件必须在同一个包下

方法三:将包内的映射器接口实现全部注册为映射器

<mappers>
  <package name="com.jiutong.dao"/>
</mappers>

注意点:

  • 接口和它的Mapper配置文件必须同名
  • 接口和它的Mapper配置文件必须在同一个包下

方法四:使用完全限定资源定位符(URL)不建议使用

<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  <mapper url="file:///var/mappers/BlogMapper.xml"/>
  <mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>

3、生命周期和作用域

作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题。

SqlSessionFactoryBuilder:

  • 一旦创建了 SqlSessionFactory,就不再需要它了
  • 局部方法变量

SqlSessionFactory:

  • 可以理解成:数据库连接池
  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
  • 因此 SqlSessionFactory 的最佳作用域是应用作用域
  • 最简单的就是使用单例模式或者静态单例模式

SqlSession:

  • 可以理解成:连接池的一个请求
  • qlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
  • 用完就立即关闭

Guess you like

Origin www.cnblogs.com/lvsafe/p/12556509.html