mybatis学习笔记1

学习整理笔记

1.创建mybatis第一个程序步骤

第一步

先导包

导入mybatis的jar包

应为要连接mysql数据库所以也要导入数据库的jar包

第二步

在src目录下创建 mybatis-config.xml配置文件

内容参考文档的内容

从xml中构建sqlsessionfactory

<?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>
  <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="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

修改相关内容

修改后为

<?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>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
          //数据库的驱动
        <property name="driver" value="com.mysql.jdbc.Driver"/>
          //数据库的地址
        <property name="url" value="jdbc:mysql://loaclhost:3306/mybatis"/>
          //数据库的用户名
        <property name="username" value="root"/>
          //数据库用户名对应的密码
        <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>
    //mybatis是把sql语句放到配置文件中,而不写到java类中
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

第三步

编写User对象

public class User {
    private Integer id;
    private String lastName;
    private String sex;

    public User() {
    }

    public User(Integer id, String lastName, String sex) {
        this.id = id;
        this.lastName = lastName;
        this.sex = sex;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", lastName='" + lastName + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

第四步

编写Mapper接口

public interface UserMapper{
    public User queryUserById(Integer id);
}

第五步

在mapper接口同一个包下创建对应的sql配置文件UserMapper.xml 参考文档中的内容主要用来执行sql语句

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
mapper 就是映射,    映射mapper接口的方法和sql语句的对应关系
    namespace名称空间/命名空间
        必须是Mapper接口全类名
-->
<mapper namespace="com.atguigu.mybatis.hello.mapper.UserMapper">
<!--    public User queryUserById(Integer id);-->
    <!--
        select标签表示配置select查询语句
            id是唯一标识.一定要跟mapper接口中的方法名一致
            parameterType 属性表示参数类型( 可选设置,如果是JavaBean,推荐设置 )
                    parameterType="int"( 可省略 )
            resultType 属性表示返回值的类型

            #{id} 表示占位符参数 ?
    -->
    <select id="queryUserById" resultType="com.atguigu.mybatis.hello.pojo.User">
        -- 必须要加别名 注意要和类中的属性名一直,不然无法识别
        select `id`,`last_name` lastName,`sex` from t_user where id = #{id}
    </select>

</mapper>

同时配置mybatis-config.xml中的mappers 与sql语句连接

<?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>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
          //数据库的驱动
        <property name="driver" value="com.mysql.jdbc.Driver"/>
          //数据库的地址
        <property name="url" value="jdbc:mysql://loaclhost:3306/mybatis"/>
          //数据库的用户名
        <property name="username" value="root"/>
          //数据库用户名对应的密码
        <property name="password" value="123456"/>
      </dataSource>
    </environment>
  </environments>
    //mybatis是把sql语句放到配置文件中,而不写到java类中
  <mappers>
    <mapper resource="com/atguigu/mybatis/hello/mapper/UserMapper.xml"/>
  </mappers>
</configuration>

第六步

进行测试

import com.atguigu.mybatis.hello.mapper.UserMapper;
import com.atguigu.mybatis.hello.pojo.User;
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;

public class MybatisTest {

    @Test
    public void test() throws IOException {
		//有mybatis-config.xml配置文件,先构建SqlSessionFactory对象实例
        //读取mybatis-config.xml配置文件
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
		//相当于 以前的jdbc编程的Connection联觉对象  用完即关
        SqlSession sqlSession = sqlSessionFactory.openSession();
        
        try {
			//获取指定类型的Mapper接口的实现类
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);

            User user = mapper.queryUserById(1);

            System.out.println( user );

        } finally {
            sqlSession.close();
        }
    }
}

注意事项

1.Mapper接口和Mapper.xml配置文件在同一个包下

2.Mapper接口文件名要和Mapper.xml文件名要一致

3.Mapper.xml配置文件名的名称空间去之一定是Mapper接口的全类名

4.Maaper.xml配置文件中的id值一定要和mapper接口的方法名一致

5.mapper.xml配置文件中的放回类型一定要和mapper接口的参数类型一致

6.Mapper.xml配置文件中的返回值类型必须要和Mapper接口的返回值类型一致

2.给mybatis程序添加日志操作

你可以通过在包、映射类的全限定名、命名空间或全限定语句名上开启日志功能,来查看 MyBatis 的日志语句。

再次提醒,具体配置步骤取决于日志实现。接下来我们会以 Log4J 作为示范。配置日志功能非常简单:添加一个或多个配置文件(如 log4j.properties),有时还需要添加 jar 包(如 log4j.jar)。下面的例子将使用 Log4J 来配置完整的日志服务。一共两个步骤:

第一步

先导入jar包

log4j-1.2.17.jar

第二步

原log4j.properties

# 全局日志配置
log4j.rootLogger=ERROR, stdout
# MyBatis 日志配置
log4j.logger.org.mybatis.example.BlogMapper=TRACE
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

在src源码目录下创建log4j.properties

# 全局日志配置
log4j.rootLogger=DEGUG, stdout
# 控制台输出
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

3.mybatis的增删改查实现

UserMapper接口

package com.atguigu.mybatis.hello.mapper;

import com.atguigu.mybatis.hello.pojo.User;

import java.util.List;

/**
 * 编写mapper接口
 * @Author:Chenshicheng
 * @create:21:19 2020/12/11
 */
public interface UserMapper {
    public User queryUserById(Integer id);
    public List<User> queryUsers();
    public int saveUser(User user);
    public int updateUser(User user);
    public int deleteUserById(Integer id);
}

UserMapper.xml配置文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
mapper 就是映射,    映射mapper接口的方法和sql语句的对应关系
    namespace名称空间/命名空间
        必须是Mapper接口全类名
-->

<mapper namespace="com.atguigu.mybatis.hello.mapper.UserMapper">
    <!--    public User queryUserById(Integer id);-->
    <!--
        select标签表示配置select查询语句
            id是唯一标识.一定要跟mapper接口中的方法名一致
            parameterType 属性表示参数类型( 可选设置,如果是JavaBean,推荐设置 )
                    parameterType="int"( 可省略 )
            resultType 属性表示返回值的类型

            #{id} 表示占位符参数 ?
    -->
    <select id="queryUserById" resultType="com.atguigu.mybatis.hello.pojo.User">
    select `id`,`last_name` lastname,`sex` from t_user where #{id}
  </select>
    <!--public List<User> queryUsers();-->
    <select id="queryUsers" resultType="com.atguigu.mybatis.hello.pojo.User">
        select `id`,`last_name` lastname,`sex` from t_user
    </select>
    <!--public int saveUser(User user);-->
    <insert id="saveUser" parameterType="com.atguigu.mybatis.hello.pojo.User">
        insert into t_user(`last_name`,`sex`)values(#{lastname},#{sex})
    </insert>
    <!--public int updateUser(User user);-->
    <update id="updateUser" parameterType="com.atguigu.mybatis.hello.pojo.User">
        update t_user set`last_name`=#{lastname},`sex`=#{sex}where id=#{id}
    </update>
    <!--public int deleteUserById(Integer id);-->
    <delete id="deleteUserById" parameterType="com.atguigu.mybatis.hello.pojo.User">
        delete from t_user where id=#{id}
    </delete>
</mapper>

测试代码

package com.atguigu.mybatis.hello.test;

import com.atguigu.mybatis.hello.mapper.UserMapper;
import com.atguigu.mybatis.hello.pojo.User;
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.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author:Chenshicheng
 * @create:18:57 2020/12/14
 */
public class MybatisTest {
        static SqlSessionFactory sqlSessionFactory;
        /**
         * @Before注解表示的方法会在测试方法之前执行。
         */
        @Before
        public void init() throws IOException {
            //由mybatis-config.xml配置文件,先构建SqlSessionFactory对象实例
            //读取mybatis-config.xml配置文件
            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        }
        @Test
    public void queryUserById() throws Exception{
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //相当于以前jdbc编程的Connection连接对---》用完即关
            try {
                //获取指定类型的实现类
                UserMapper mapper = sqlSession.getMapper(UserMapper.class);
                User user = mapper.queryUserById(1);
                System.out.println(user);
            } finally {
                sqlSession.close();
            }

        }
    @Test
    public void saveUser() {

        //1 通过SqlSessionFactory对象获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            //2 通过SqlSession 获取Mapper接口( 代理 )
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //3 调用接口方法
            int count = mapper.saveUser(new User(null, "wzg168", 1));

            System.out.println(" 影响的行数 => " + count);

            sqlSession.commit();//手动提交事务
        } finally {
            // 4 关闭SqlSession对象
            sqlSession.close();
        }

    }
    @Test
    public void updataUser(){
            //通过SqlSessionFactory对象获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            //通过SqlSession获取    Mapper接口(代理)
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //调用接口的方法
            mapper.updateUser(new User(2,"abc168",0));
            //手动提交事务
            sqlSession.commit();
        } finally {
            //关闭SqlSession对象
            sqlSession.close();
        }
    }
    @Test
    public void queryUsers(){
            //通过SqlSessionFactory对象获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            //通过SqkSession获取Mapper接口(代理)
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //调用接口的方法
            //查询多条语句 需要要用增强for进行语句的显示
            for (User queryUser : mapper.queryUsers()) {
                System.out.println(queryUser);
            }
        } finally {
            //关闭SqlSession对象
            sqlSession.close();
        }

    }
    @Test
    public void deleteUserById(){
            //通过SqlSessionFactory获取SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        try {
            //通过SqlSession获取Mapper接口(代理)
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            //调用接口的方法
            mapper.deleteUserById(3);
            //手动提交事务
            sqlSession.commit();
        } finally {
            //关闭SqlSession对象
            sqlSession.close();
        }
    }
}

插入记录并返回主键

 <!--public int saveUser(User user);
        useGeneratedKeys="true"表示使用
        keyProperty="id"是指将返回的主键id值,注入到参数那个属性中
    -->
    <insert id="saveUser" useGeneratedKeys="true" keyProperty="id"
            parameterType="com.atguigu.mybatis.hello.pojo.User">
        insert into t_user(`last_name`,`sex`) values(#{lastName},#{sex})
    </insert>

标签的使用

selectKey标签,它可以在语句的标签里面再定义一个查询语句。

这个查询语句,主要用于查询生成的主键

<insert id="saveUser" parameterType="com.atguigu.mybatis.hello.pojo.User">
    <!--
        order属性设置两个语句的执行顺序(selectKey语句的执行顺序)
            BEFORE 先执行selectKey的语句
            AFTER   后执行selectKey的语句
        keyProperty="id"是指将返回的主键id值,注入到参数的哪个属性中
        resultType="int" 返回的是Integer类型
    -->
    <selectKey order="AFTER" keyProperty="id" resultType="int">
        select last_insert_id();
    </selectKey>
        insert into t_user(`last_name`,`sex`) values(#{lastName},#{sex})
    </insert>

在oracle数据库中的用法

<selectKey order="BEFORE" resultType="int" keyProperty="id"> 
             select 序列名.nextval as id from dual 
         </selectKey>

4.注解@MapKey的使用

@MapKey可以把返回的结果转换为map对象,并且指定一个属性作为key

(key是唯一的,所以指定的属性值也要是唯一的)

Mapper接口:

@MapKey("id")
public Map<Integer,User> queryUsersForMap();

Mapper.xml配置文件:

<select id="queryUsersForMap" resultType="com.atguigu.mybatis.hello.pojo.User">
        select `id`,`last_name` lastName,`sex` from t_user
    </select>

测试代码

@Test
public void queryUsersForMap(){
    //1 通过SqlSessionFactory对象获取SqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        //2 通过SqlSession 获取Mapper接口( 代理 )
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //3 调用接口方法
        Map<Integer, User> integerUserMap = mapper.queryUsersForMap();

        for (Map.Entry<Integer, User> entry : integerUserMap.entrySet()) {
            System.out.println( entry );
        }

    } finally {
        // 4 关闭SqlSession对象
        sqlSession.close();
    }
}

5.mybatis的核心配置之properties

第一种表现形式

 <properties >
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <!--数据库的地址-->
        <property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </properties>

第二种表现形式

需要进行配置jdbc.properties

  <properties resource="jdbc.properties">
  </properties>

在dataSource中的代码为

<dataSource type="POOLED">
                <!--数据库的驱动-->
                <property name="driver" value="${driver}"/>
                <!--数据库的地址-->
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>

jdbc.properties中的代码为

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis
username=root
password=123456

6.mybatis的核心配置之settings

这是MyBatis中极为重要的调整设置,它们会改变MyBatis的运行时行为。下表描述了设置中各项的意图与默认值

所有mybatis的settings设置选项

设置参数描述有效值
cacheEnabled该配置影响的所有映射器中配置的缓存的全局开关。true | false
lazyLoadingEnabled延迟加载的全局开关。当开启时,所有关联对象都会延迟加载。 特定关联关系中可通过设置fetchType属性来覆盖该项的开关状态。true | false
aggressiveLazyLoading当启用时,对任意延迟属性的调用会使带有延迟加载属性的对象完整加载;反之,每种属性将会按需加载。true | false
multipleResultSetsEnabled是否允许单一语句返回多结果集(需要兼容驱动)。true | false
useColumnLabel使用列标签代替列名。不同的驱动在这方面会有不同的表现, 具体可参考相关驱动文档或通过测试这两种不同的模式来观察所用驱动的结果。true | false
useGeneratedKeys允许 JDBC 支持自动生成主键,需要驱动兼容。 如果设置为 true 则这个设置强制使用自动生成主键,尽管一些驱动不能兼容但仍可正常工作(比如 Derby)。true | false
autoMappingBehavior指定 MyBatis 应如何自动映射列到字段或属性。 NONE 表示取消自动映射;PARTIAL 只会自动映射没有定义嵌套结果集映射的结果集。 FULL 会自动映射任意复杂的结果集(无论是否嵌套)。NONE, PARTIAL, FULL
autoMappingUnknownColumnBehaviorSpecify the behavior when detects an unknown column (or unknown property type) of automatic mapping target. · NONE: Do nothing · WARNING: Output warning log (The log level of'org.apache.ibatis.session.AutoMappingUnknownColumnBehavior'must be set to WARN) · FAILING: Fail mapping (Throw SqlSessionException)NONE, WARNING, FAILING
defaultExecutorType配置默认的执行器。SIMPLE 就是普通的执行器;REUSE 执行器会重用预处理语句(prepared statements); BATCH 执行器将重用语句并执行批量更新。SIMPLE REUSE BATCH
defaultStatementTimeout设置超时时间,它决定驱动等待数据库响应的秒数。Any positive integer
defaultFetchSizeSets the driver a hint as to control fetching size for return results. This parameter value can be override by a query setting.Any positive integer
safeRowBoundsEnabled允许在嵌套语句中使用分页(RowBounds)。 If allow, set the false.true | false
safeResultHandlerEnabled允许在嵌套语句中使用分页(ResultHandler)。 If allow, set the false.true | false
mapUnderscoreToCamelCase是否开启自动驼峰命名规则(camel case)映射,即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。true | false
localCacheScopeMyBatis 利用本地缓存机制(Local Cache)防止循环引用(circular references)和加速重复嵌套查询。 默认值为 SESSION,这种情况下会缓存一个会话中执行的所有查询。 若设置值为 STATEMENT,本地会话仅用在语句执行上,对相同 SqlSession 的不同调用将不会共享数据。SESSION | STATEMENT
jdbcTypeForNull当没有为参数提供特定的 JDBC 类型时,为空值指定 JDBC 类型。 某些驱动需要指定列的 JDBC 类型,多数情况直接用一般类型即可,比如 NULL、VARCHAR 或 OTHER。JdbcType enumeration. Most common are: NULL, VARCHAR and OTHER
lazyLoadTriggerMethods指定哪个对象的方法触发一次延迟加载。A method name list separated by commas
defaultScriptingLanguage指定动态 SQL 生成的默认语言。A type alias or fully qualified class name.
callSettersOnNulls指定当结果集中值为 null 的时候是否调用映射对象的 setter(map 对象时为 put)方法,这对于有 Map.keySet() 依赖或 null 值初始化的时候是有用的。注意基本类型(int、boolean等)是不能设置成 null 的。true | false
logPrefix指定 MyBatis 增加到日志名称的前缀。Any String
logImpl指定 MyBatis 所用日志的具体实现,未指定时将自动查找。SLF4J | LOG4J | LOG4J2 | JDK_LOGGING | COMMONS_LOGGING | STDOUT_LOGGING | NO_LOGGING
proxyFactory指定 Mybatis 创建具有延迟加载能力的对象所用到的代理工具。CGLIB | JAVASSIST
vfsImplSpecifies VFS implementationsFully qualified class names of custom VFS implementation separated by commas.
useActualParamNameAllow referencing statement parameters by their actual names declared in the method signature. To use this feature, your project must be compiled in Java 8 with -parameters option. (Since: 3.4.1)true | false

7.mybatis的核心配置之typeAliases

我们在编写sql的配置文件中,经常会出现大量的相同的全类名。这些全类名都是一样的字符串,我们就可以给一个类型去定义一个简短的别名。去使用这个别名表示一个具体类型

 <!--typeAliases定义多个别名-->
<typeAliases>
        <!--
            type属性是全类名
            alias属性指定别名

        <typeAlias type="com.atguigu.mybatis.hello.pojo.User" alias="user"/>
        -->
        <!--
            指定包名,Mybatis回自动扫描这个包下的所有的类,自动映射别名
            别名,就是他的类名,或类名首字母小写
            com.atguigu.mybatis.hello.pojo.User ===>>>User 或user
        -->
        <package name="com.atguigu.mybatis.hello.pojo.User"/>
        <package name="com.atguigu.mybatis.hello.domain.User"/>
    </typeAliases>

在以后工作中如果遇到在不同包 内有相同的JavaBean类名那么需要在JavaBean前面使用

@Alias()注解

指定别名,避免别名冲突

package com.atguigu.mybatis.hello.domain;

import org.apache.ibatis.type.Alias;

/**
 * @Author:Chenshicheng
 * @create:21:09 2020/12/11
 */
@Alias("doUser")
public class User {
    private Integer id;
    private String lastName;
    private Integer sex;

    public User() {
    }

8.mybatis的核心配置之typeHandlers

类型处理器Java 类型JDBC 类型
BooleanTypeHandlerjava.lang.Boolean, boolean数据库兼容的 BOOLEAN
ByteTypeHandlerjava.lang.Byte, byte数据库兼容的 NUMERICBYTE
ShortTypeHandlerjava.lang.Short, short数据库兼容的 NUMERICSHORT INTEGER
IntegerTypeHandlerjava.lang.Integer, int数据库兼容的 NUMERICINTEGER
LongTypeHandlerjava.lang.Long, long数据库兼容的 NUMERICLONG INTEGER
FloatTypeHandlerjava.lang.Float, float数据库兼容的 NUMERICFLOAT
DoubleTypeHandlerjava.lang.Double, double数据库兼容的 NUMERICDOUBLE
BigDecimalTypeHandlerjava.math.BigDecimal数据库兼容的 NUMERICDECIMAL
StringTypeHandlerjava.lang.StringCHAR, VARCHAR
ClobReaderTypeHandlerjava.io.Reader-
ClobTypeHandlerjava.lang.StringCLOB, LONGVARCHAR
NStringTypeHandlerjava.lang.StringNVARCHAR, NCHAR
NClobTypeHandlerjava.lang.StringNCLOB
BlobInputStreamTypeHandlerjava.io.InputStream-
ByteArrayTypeHandlerbyte[]数据库兼容的字节流类型
BlobTypeHandlerbyte[]BLOB, LONGVARBINARY
DateTypeHandlerjava.util.DateTIMESTAMP
DateOnlyTypeHandlerjava.util.DateDATE
TimeOnlyTypeHandlerjava.util.DateTIME
SqlTimestampTypeHandlerjava.sql.TimestampTIMESTAMP
SqlDateTypeHandlerjava.sql.DateDATE
SqlTimeTypeHandlerjava.sql.TimeTIME
ObjectTypeHandlerAnyOTHER 或未指定类型
EnumTypeHandlerEnumeration TypeVARCHAR-任何兼容的字符串类型,存储枚举的名称(而不是索引)
EnumOrdinalTypeHandlerEnumeration Type任何兼容的 NUMERICDOUBLE 类型,存储枚举的索引(而不是名称)。

9.mybatis的核心配置之environments

MyBatis 可以配置成适应多种环境,这种机制有助于将 SQL 映射应用于多种数据库之中

注意:尽管可以配置多个环境,但每个 SqlSessionFactory 实例只能选择一种环境。

<environment id="development">
            <!--
                transactionManager表示事务管理器
                type属性指定使用哪个事务管理器
                    JDBC 有事务管理,有提交和回滚
                    MANAGED事务交给容器管理,没提交,也没回滚
            -->
            <transactionManager type="JDBC"/>
            <!--
                dataSource type="POOLED"表示使用数据库连接池技术
                UNPOOLED 不适用数据库连接池技术,每需要使用Connection连接对象的时候,再手动创建一个,用完即关
                POOLED 使用数据库连接池
            -->
            <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>

10.mybatis的核心配置之databaseldProvider

Mybatis可以根据不同的数据库厂商执行不同的语句,这种厂商支持是基于映射语句中的databaseId属性。Mybatis会加载不带datatbaseId 属性和带有匹配当前数据库 databaseId的所有语句

 <databaseIdProvider type="DB_VENDOR">
        <property name="SQL Server" value="sqlserver"/>
        <property name="MySQL" value="mysql"/>
        <property name="DB2" value="db2"/>
        <property name="Oracle" value="oracle" />
        
    </databaseIdProvider>

mybatis提供了一个类VendorDatabaseIdProvider中的getDatabaseId()方法用于获取数据库的标识。

​ property标签name属性是获取数据库ID标识。

​ property标签value属性是我们给mybatis定义的一个简短的标识.

databaseId测试

<select id="queryUsers" resultType="user" >
    select `id`,`last_name`,`sex` from t_user
</select>
<!--
    databaseId="mysql" 表示当前配置的sql语句,如果是mysql数据库,就会执行此sql语句
-->
<select id="queryUsers" resultType="user" databaseId="mysql">
    select `id`,`last_name`,`sex` from t_user where 1 = 1
</select>
<!--
    databaseId="oracle" 表示当前配置的sql语句,如果是oracle数据库,就会执行此sql语句
-->
<select id="queryUsers" resultType="user" databaseId="oracle">
    select `id`,`last_name`,`sex` from t_user where 2 = 2
</select>

11.mybatis的核心配置之Mappers

mappers标签专门用来引入sql的配置文件 mapper.xml配置文件

有四种实现形式

1.使用相对类路径的资源引用;

2.使用完全限定资源定位符(URL);不推荐

3.使用映射器接口实现类的完全限定名;

4.将包内的映射器接口实现全部注册为映射器;推荐

<!--
        Mybatis是把sql语句放到配置文件中,而不是写道java类中
    -->
    <mappers>
        <!--
            从类路径下加载mapper.xml配置文件
        -->
        <!--<mapper resource="com/atguigu/mybatis/hello/mapper/UserMapper.xml"/>-->
        <!--
            表示按接口 加载sql的配置文件
                注意事项:
                    1.mapper接口和mapper.xml 配置文件必须再同一个包下
                    2.mapper接口的类名和mapper.xml的文件名必须一致!!!
        <mapper class="com.atguigu.mybatis.hello.mapper.UserMapper"/>
        -->
        <!--
            mybatis会自动根据指定的包名,加载所有的sql配置文件
        -->
        <package name="com.atguigu.mybatis.hello.mapper"/>
    </mappers>
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值