博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Mybatis3
阅读量:4492 次
发布时间:2019-06-08

本文共 6283 字,大约阅读时间需要 20 分钟。

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;

 

转载于:https://www.cnblogs.com/wanghuaying/p/9714378.html

你可能感兴趣的文章
让oracle做定时任务【转】
查看>>
C++自学教程第一课——你好世界,我是柠檬鲸。
查看>>
idea javamaven项目 连接sqlserver 数据库方法
查看>>
Nginx Fastcgi PATH_INFO urldecode问题
查看>>
SharpGL学习笔记(十七) 立体文字和平面文字
查看>>
ccleaner注册码
查看>>
MAVEN学习-第一个Maven项目的构建
查看>>
Python之xml文档及配置文件处理(ElementTree模块、ConfigParser模块)
查看>>
jQuery的deferred对象详解
查看>>
JUnit4 入门笔记
查看>>
利用相关的Aware接口
查看>>
设计模式—建造者模式
查看>>
2-6
查看>>
猜拳游戏项目(涉及知识点Scanner、Random、For、数组、Break、Continue等)
查看>>
centos 6.3 编译安装 nginx +mysql + php
查看>>
<Web> 如何给web项目添加redis服务
查看>>
百度地图
查看>>
倒计时
查看>>
Spark shuffle详细过程
查看>>
rhel6.4 zabbix 安装时少的bcmath mbstring
查看>>