Mybatis-笔记1

什么是MyBatis
MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records.

使用MyBatis

1) 编程式
2)集成式managed 集成到spring
3)工作当中的使用方式 分析业务 、定义表结构 、generator生成需要的文件 、编程调用
4)generator使用步骤
a)pom.xml 中 build 下增加如下配置:

  <plugins>
        <plugin>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.3</version>
            <configuration>
                <configurationFile>${project.basedir}/src/main/resources/generatorConfig.xml</configurationFile>
                <overwrite>true</overwrite>
            </configuration>
        </plugin>
    </plugins>

b)配置文件内容generatorConfig:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
        PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <classPathEntry location="D:\repository\mysql\mysql-connector-java\5.1.17\mysql-connector-java-5.1.17.jar"/>
    <context id="MysqlTables" targetRuntime="MyBatis3">
        <!--去除注释  -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/test?useUnicode=true&amp;characterEncoding=utf-8&amp;useSSL=false&amp;useJDBCCompliantTimezoneShift=true&amp;useLegacyDatetimeCode=false&amp;serverTimezone=UTC"
                        userId="root"
                        password="root">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>
        <javaModelGenerator targetPackage="com.test.mybatis.beans" targetProject="D:\works\work3\mybatis\generate\src\main\java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
        </javaModelGenerator>
        <sqlMapGenerator targetPackage="xml" targetProject="D:\works\work3\mybatis\generate\src\main\resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.test.mybatis.mapper" targetProject="D:\works\work3\mybatis\generate\src\main\java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <table schema="test" tableName="user" domainObjectName="User">
            <property name="useActualColumnNames" value="false"/>
        </table>
    </context>
</generatorConfiguration>

c)执行 mvn mybatis-generator:generate 即可生成文件到指定的目录

5)主要对象作用域SCOPE 生命周期
在这里插入图片描述

6)Mapper的xml和annotation形式
userMapper 中通过注解直接定义的查询:

@Select(“select * from user where id=‘1’”)
User getMyUser();

UserMapper.xml 中定义的查询

 <select id="getMyUser" parameterType="java.lang.String" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from user
    where id = '2'
  </select>

这两者单独都可以使用但是不能同时存在(同一个方法有两种sql实现),同时存在会报异常

Caused by: java.lang.IllegalArgumentException: Mapped Statements collection already contains value for com.test.mybatis.mapper.UserMapper.getMyUser

注解和xml 两种方式对比:
在这里插入图片描述

TypeHandler
TypeHandler
MyBatis 中的 TypeHandler 类型处理器用于 JavaType 与 JdbcType 之间的转换,用于 PreparedStatement 设置参数值和从 ResultSet 或 CallableStatement 中取出一个值。MyBatis 内置了大部分基本类型的类型处理器,所以对于基本类型可以直接处理,当我们需要处理其他类型的时候就需要自定义类型处理器。
实现自定义 TypeHandler 可以 实现 TypeHandler 或继承 BaseTypeHandler

此处如果不用注解指定jdbcType, 那么,就可以在配置文件中通过"jdbcType"属性指定, 同理, javaType 也可通过 @MappedTypes指定
//@MappedJdbcTypes(JdbcType.VARCHAR)
//@MappedTypes(System.class)
public class MyTypeHandler extends BaseTypeHandler {
    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Object o, JdbcType jdbcType) throws SQLException {

    }
    @Override
    public Object getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return resultSet.getString(s)+"_fix";
    }
    @Override
    public Object getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return null;
    }
    @Override
    public Object getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return null;
    }
}

然后在 mapper.xml 中进行配置

 <resultMap id="BaseResultMap" type="com.test.mybatis.beans.User">
    <id column="id" jdbcType="VARCHAR" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" typeHandler="com.test.MyTypeHandler"/>
    <result column="sex" jdbcType="VARCHAR" property="sex" />
  </resultMap>

执行查询测试 结果中name字段内容追加了 _fix 后缀
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. MyBatis eliminates almost all of the JDBC code and manual setting of parameters and retrieval of results. MyBatis can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records. Contents What is MyBatis? .. 5 Getting Started ...... 5 Building SqlSessionFactory from XML ............. 5 Building SqlSessionFactory without XML ........ 6 Acquiring a SqlSession from SqlSessionFactory ............. 6 Exploring Mapped SQL Statements . 7 A Note about Namespaces........... 8 Scope and Lifecycle .......... 9 Mapper Configuration XML  10 properties ........ 11 settings ............ 12 typeAliases ...... 13 typeHandlers ... 14 objectFactory .. 15 plugins ............. 16 environments .. 17 transactionManager .... 18 dataSource .. 19 mappers .......... 21 SQL Map XML Files ............. 21 select  22 insert, update, delete ...... 24 sql ..... 26 Parameters ...... 26 MyBatis 3 - User Guide 5 November 2010 4 resultMap ........ 28 Advanced Result Mapping ......... 30 id, result ...... 32 Supported JDBC Types  33 constructor .. 33 association .. 34 collection ..... 37 discriminator .............. 40 cache  41 Using a Custom Cache . 43 cache-ref ......... 44 Dynamic SQL ....... 44 if ....... 44 choose, when, otherwise  45 trim, where, set .............. 45 foreach ............ 47 Java API  49 Directory Structure ........ 49 SqlSessions ...... 50 SqlSessionFactoryBuilder ........... 50 SqlSessionFactory....... 52 SqlSession .... 54 SelectBuilder ....... 60 SqlBuilder ............ 63
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

catch that elf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值