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

  • 相关阅读:
    507. Perfect Number
    Dos与Linux的断行字符
    724. Find Pivot Index
    110. Balanced Binary Tree
    掌握numpy(三)
    掌握numpy(二)
    掌握numpy(一)
    203. Remove Linked List Elements
    25个Java机器学习工具和库
    贝叶斯学习--极大后验概率假设和极大似然假设
  • 原文地址:https://www.cnblogs.com/man-tou/p/11335402.html
Copyright © 2011-2022 走看看