zoukankan      html  css  js  c++  java
  • Mybatis3

    1      Mybatis扩展

    1.1     example查询

    1.2     分页插件

    1.3      注解

    1.4     自定义类型转化器

    2      Mapper接口

    Example:where后的条件

    方法   

    功能说明

    int countByExample(XXXExample example) thorws SQLException

    按条件计数

    int deleteByPrimaryKey(Integer id) SQLException

    按主键删除

    int deleteByExample(XXXExample example) thorws SQLException

    按条件删除

    String/Integer insert(XXX record) thorws SQLException

    插入数据

    XXX selectByPrimaryKey(Integer id) thorws SQLException

    按主键查询

    ListselectByExample(XXXExample example) thorws SQLException

    按条件查询

    ListselectByExampleWithBLOGs(XXXExample example) thorws SQLException

    按条件查询(包括BLOB字段)。只有当数据表中的字段类型有为二进制的才会产生。

    int updateByPrimaryKey(XXX record) thorws SQLException

    按主键更新

    int updateByPrimaryKeySelective(XXX record) thorws SQLException

    按主键更新值不为null的字段

    int updateByExample(XXX record, XXXExample example) thorws SQLException

    按条件更新

    int updateByExampleSelective(XXX record, XXXExample example) thorws SQLException

    按条件更新值不为null的字段

     

      注意:

      int updateByExampleSelective(@Param("record") Pets record, @Param("example") PetsExample example);

    /**

         * 使用@Param("record") 注解,可以把参数封装成Map<String,Object>

         * @Param("record") Pets record, @Param("example") 相当于

         *

         * Map<String,Object> map = new HashMap(String,Object);

         * map.put("record",record);

         * map.put("example",example);

         */

    上述方法中的@Param注解

    mybatis会把参数封装成Map对象,键为注解的参数,值为方法的参数

    3      example实例解析

    mybatis的逆向工程中会生成实例及实例对应的example,example用于添加条件,相当where后面的部分 
    xxxExample example = new xxxExample(); 
    Criteria criteria = example .createCriteria();

    方法

    说明

    example.setOrderByClause(“字段名 ASC”);

    添加升序排列条件,DESC为降序

    example.setDistinct(false)

    去除重复,boolean型,true为选择不重复的记录。

    criteria.andXxxIsNull

    添加字段xxx为null的条件

    criteria.andXxxIsNotNull

    添加字段xxx不为null的条件

    criteria.andXxxEqualTo(value)

    添加xxx字段等于value条件

    criteria.andXxxNotEqualTo(value)

    添加xxx字段不等于value条件

    criteria.andXxxGreaterThan(value)

    添加xxx字段大于value条件

    criteria.andXxxGreaterThanOrEqualTo(value)

    添加xxx字段大于等于value条件

    criteria.andXxxLessThan(value)

    添加xxx字段小于value条件

    criteria.andXxxLessThanOrEqualTo(value)

    添加xxx字段小于等于value条件

    criteria.andXxxIn(List<?>)

    添加xxx字段值在List<?>条件

    criteria.andXxxNotIn(List<?>)

    添加xxx字段值不在List<?>条件

    criteria.andXxxLike(“%”+value+”%”)

    添加xxx字段值为value的模糊查询条件

    criteria.andXxxNotLike(“%”+value+”%”)

    添加xxx字段值不为value的模糊查询条件

    criteria.andXxxBetween(value1,value2)

    添加xxx字段值在value1和value2之间条件

    criteria.andXxxNotBetween(value1,value2)

    添加xxx字段值不在value1和value2之间条件

    4      分页插件

    1. pom.xml文件中添加分页插件

    <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->

    <dependency>

        <groupId>com.github.pagehelper</groupId>

        <artifactId>pagehelper</artifactId>

        <version>4.1.6</version>

    </dependency>

     

    2. mybatis配置文件中添加分页插件

       <plugins>

                   <plugin interceptor="com.github.pagehelper.PageHelper">

                            <property name="dialect" value="mysql"/>

                   </plugin>

                    <!--5.0版本pagehelper-->

                      <!-- <plugin interceptor="com.github.pagehelper.PageInterceptor">

                                       <property name="helperDialect" value="mysql"/>

                      </plugin> -->

      </plugins>

     

    3. 测试类中使用PageHelper分页查询

            PageHelper.startPage(2, 4);

                      List<Pets> list1  = mapper.selectByExample(null);

                      PageInfo<Pets> pageInfo = new PageInfo<Pets>(list1);

                      System.out.println(list1);

                      List<Pets> list2 = pageInfo.getList();

                      System.out.println(list2);

                      for (Pets pets : list2) {

                              System.out.println(pets);

                      }

    4   mybatis注解开发

    public interface PetsMapper {

        

         @Select(value="select id,name,birth_date birthDate,type_id typeId, owner_id ownerId from pets")

         public List<Pets> findAll();

        

         @Select("select id,name,birth_date birthDate,type_id typeId, owner_id ownerId from pets where id=#{id}")

         public Pets findById(int id);

        

         @Insert("insert into pets(name,birth_date,type_id,owner_id) values(#{name},#{birthDate},#{typeId},#{ownerId})")

    @SelectKey(keyColumn="id",keyProperty="id",resultType=Integer.class, before = false, statement = { "select last_insert_id()" })

         public int insert(Pets p);

        

         @Update(value="update pets set name=#{name},birth_date=#{birthDate} where id=#{id}")

         public int update(Pets p);

        

         @Delete("delete from pets where id=#{id}")

         public int delete(int id) ;

       

    }

    5  mybatis自定义类型处理器

    场景:当字段类型和数据库类型不一致时,需要自定义类型转化器。

    使用:

           1)编写一个普通类继承BaseTypeHandler<T>抽象类,或者实现TypeHandler<T>接口。重写三个方法:如下:

          

    /**

    *TODO自定义类型处理器

    *    遇到Address类型的字段,会自动来调用该类中的方法

    *    1)新增 修改  :Address对象--->String

              调用setNonNullParameter() 方法 处理address类型的字段

    *    2)查询:   把varchar类型的address--->Address类型

    *    调用getNullableResult/getNullableResult

    *    把数据库的address 重新封装成Address类型

    */

    public class MyAddressTypeHandler extends  BaseTypeHandler<Address> {

     

         /**

          * 新增 或者修改时  遇到Address 类型的字段 自动会调用该方法

          */

         @Override

         public void setNonNullParameter(PreparedStatement ps, int i, Address parameter, JdbcType jdbcType)

                   throws SQLException {

                   //填充address这个字段的占位符

                   ps.setString(i, parameter.toString());//对象--->字符串

         }

         /**

          * 根据列名查询

          */

         @Override

         public Address getNullableResult(ResultSet rs, String columnName) throws SQLException {

              // TODO Auto-generated method stub

              String a  = rs.getString(columnName);

              //山东省-青岛市-市北区-市北路-100(String)

              Address address = null;

              if (a!=null) {

                   String s [] = a.split("-");

                   address = new Address();

                   address.setProvinceName(s[0]);

                   address.setCityName(s[1]);

                   address.setDistinctName(s[2]);

                   address.setStreetName(s[3]);

                   address.setNo(Integer.parseInt(s[4].trim()));

              }

              return  address;

         }

         /**

          * 根据下标查询

          */

         @Override

         public Address getNullableResult(ResultSet rs, int columnIndex) throws SQLException {

                        String a  = rs.getString(columnIndex);

                        //山东省-青岛市-市北区-市北路-100(String)

                        Address address = null;

                        if (a!=null) {

                             String s [] = a.split("-");

                             address = new Address();

                             address.setProvinceName(s[0]);

                             address.setCityName(s[1]);

                             address.setDistinctName(s[2]);

                             address.setStreetName(s[3]);

                             address.setNo(Integer.parseInt(s[4].trim()));

                        }

                        return  address;

         }

     

         /**

          * 存储过程

          */

         @Override

         public Address getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {

              // TODO Auto-generated method stub

              return null;

         }

    2)在mybatis的配置文件中配置该处理器

    <!-- 自定义类型处理器 -->

        <typeHandlers>

           <!-- 配置自定义类型处理器

              配置完成后:遇到address类型的字段 自动会调用MyAddressTypeHandler类处理该字段

           -->

           <typeHandler handler="com.itqf.handler.MyAddressTypeHandler"/>

        </typeHandlers>

    6    Mybatis中#{}和${}的使用

    #{}

                按照该字段真实的值的类型填充占位符。例如:String类型,调用ps.setString()填充。

    ${}

                直接把值拼接到sql语句中,不拼接链接符号。

    存在sql注入的问题

    应用场景:排序时,要排序的字段,排序规则,就可以使用${}

    排序:

    select  * from   users order by #{order} #{sorter};

    使用#{}方式,执行sql语句

    select * from users order by 'id' 'desc';

     

    select  * from   users order by ${order} ${sorter};

    使用${}方式,执行sql语句

    select * from users order by id desc;

     

  • 相关阅读:
    002powershell使用常见问题
    028_如何外网下载大文件
    028MAC常用工具unlicense
    027_录屏倒计时弹窗实用小程序
    NIO相关基础篇
    写给刚上小学一年级的果果(家长寄语)
    [转]Mavlink协议
    [原][ARCGIS]使用ARCMAP分离导出单个矢量图形文件SHP
    [原][译]从osgEarth2升级到osgEarth3的变化
    [减肥]生酮减肥餐做法
  • 原文地址:https://www.cnblogs.com/wanghuaying/p/9714378.html
Copyright © 2011-2022 走看看