zoukankan      html  css  js  c++  java
  • 04.MyBatis别名的设置和类型转换器

    别名的设置:(别名不区分大小写):

    设置单个别名:

    <configuration>
        <properties resource="db.properties" />
        <typeAliases>
            <!-- 设置单个别名 -->
            <typeAlias type="com.offcn.entity.Person" alias="person"/>
            <typeAlias type="com.offcn.entity.Book" alias="book"/>
        </typeAliases>

    映射文件中直接写别名即可:

    <select id="queryPersonById" parameterType="int" resultType="person">
        select * from person where id = #{id}
    </select>

    批量设置别名:

    <typeAliases>
       <!-- 批量定义别名 ,别名不区分大小写,会将该包下的所有文件批量设置别名-->
        <package name="com.offcn.entity"/>
    </typeAliases>

    类型转换器:


    1.MyBatis自带的类型转换器:

    2.自定义的类型转换器:

    步骤:

    a.创建转换器:需要实现TypeHandler接口,实现转换器有两种方式:

      i.实现接口TypeHandler

      ii.继承BaseTypeHander

    创建converter转换器,代码如下:

    package com.offcn.converter;
    
    import java.sql.CallableStatement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    import org.apache.ibatis.type.BaseTypeHandler;
    import org.apache.ibatis.type.JdbcType;
    
    public class BooleanToIntConverter extends BaseTypeHandler<Boolean>{
        //DB ---> java
        @Override
        //根据名字拿
        public Boolean getNullableResult(ResultSet rs, String columnName) throws SQLException {
            // TODO Auto-generated method stub
            int sexNo = rs.getInt(columnName);
            return sexNo == 1?true:false;
        }
        //根据下标拿
        @Override
        public Boolean getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
            // TODO Auto-generated method stub
            int sexNo = rs.getInt(columnIndex);
            return sexNo == 1?true:false;
        }
        //根据存储过程拿
        @Override
        public Boolean getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
            // TODO Auto-generated method stub
            int sexNo = cs.getInt(columnIndex);
            return sexNo == 1?true:false;
        }
        //java ---> DB
        @Override
        public void setNonNullParameter(PreparedStatement ps, int i, Boolean parameter, JdbcType jdbc) throws SQLException {
            // TODO Auto-generated method stub
            if(parameter) {
                ps.setInt(i, 1);
            }else {
                ps.setInt(i, 0);
            }
        }
    
    }

    在conf.xml文件中配置类型转换器:

    <typeHandlers>
            <typeHandler handler="com.offcn.converter.BooleanToIntConverter" javaType="Boolean" jdbcType="INTEGER"/>
    </typeHandlers>

    映射文件中查找的sql:(DB ---> JAVA)

    <!-- 带类型转换器的查询 -->
       <select id="queryPersonByIdWithConverter" parameterType="int" resultMap="personResult">
        select * from person where id = #{id}
      </select>
      <resultMap type="person" id="personResult">
          <!-- 分为主键和非主键,主键用id,非主键用result -->
          <id property="id" column="id"/>
          <result property="name" column="name"/>
          <result property="bir" column="bir"/>
          <result property="address" column="address"/>
          <result property="sex" column="sex" javaType="Boolean" jdbcType="INTEGER" />
      </resultMap>

    接口中定义对应的方法:

    Person queryPersonByIdWithConverter(int id);

    测试类进行测试:

    public static void queryPersonByIdWithConverter() throws IOException {
            //读取conf.xml文件
            Reader reader = Resources.getResourceAsReader("conf.xml");
            //创建sqlSessionFactory
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            //获取sqlSession
            SqlSession session = sessionFactory.openSession();
            //通过session定位映射文件
            personMapper personMapper = session.getMapper(personMapper.class);
            //定位sql语句并执行
            Person person = personMapper.queryPersonByIdWithConverter(4);
            //提交事务
            session.commit();
            System.out.println(person);
            //关闭连接
            session.close();
        }

    映射文件中增加的sql:(JAVA --> DB)

    <!-- 带类型转转器的增加 -->
      <insert id="insertPersonWithConverter" parameterType="person" >
          insert into person (name,bir,address,sex) value (#{name},#{bir},#{address},#{sex,javaType=Boolean,jdbcType=INTEGER})
      </insert>

    接口中定义对应的方法:

    测试类进行测试:

    //带转换器的增加操作
        public static void insertPersonWithConverter() throws IOException {
            //读取conf.xml文件
            Reader reader = Resources.getResourceAsReader("conf.xml");
            //获取sqlSessionFactory
            SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);
            //获取sqlSession
            SqlSession session = sessionFactory.openSession();
            //定位映射文件的位置
            personMapper personMapper = session.getMapper(personMapper.class);
            //定位sql并执行
            Person person = new Person("小孙",new Date(),"青岛",true);
            personMapper.insertPersonWithConverter(person);
            //提交事务
            session.commit();
            System.out.println("增加成功");
            //关闭连接
            session.close();
        }

    最后关于:sql标签中什么时候用resultType什么时候用resultMap

    1.如果表中字段和实体类中的属性的类型合理识别,则用resultType,否则用resultMap

    2.如果表中字段的名字和实体类中属性名能够合理识别,则用resultType,否则用resultMap

  • 相关阅读:
    彻底理解Netty
    linux netstat 统计连接数查看
    log4j2 自动删除过期日志文件配置及实现原理解析
    Log4j2的Policy触发策略与Strategy滚动策略配置详解
    @Accessors
    Caffeine Cache实战
    ws协议与http协议的异同
    深入理解Java:注解(Annotation)自定义注解入门
    java日志框架
    springboot 集成J2Cache
  • 原文地址:https://www.cnblogs.com/man-tou/p/11335402.html
Copyright © 2011-2022 走看看