一、新建项目及配置
1.1 新建一个SpringBoot项目,并在pom.xml下加入以下代码
<dependency>
<groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.0.1</version> </dependency>
application.properties文件下配置(使用的是MySql数据库)
# 注:我的SpringBoot 是2.0以上版本,数据库驱动如下
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/database?characterEncoding=utf8&serverTimezone=UTC spring.datasource.username=your_username spring.datasource.password=your_password
# 可将 com.dao包下的dao接口的SQL语句打印到控制台,学习MyBatis时可以开启
logging.level.com.dao=debug
SpringBoot启动类Application.java 加入@SpringBootApplication 注解即可(一般使用该注解即可,它是一个组合注解)
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
之后dao层的接口文件放在Application.java 能扫描到的位置即可,dao层文件使用@Mapper注解
@Mapper public interface UserDao { /** * 测试连接 */ @Select("select 1 from dual") int testSqlConnent(); }
测试接口能返回数据即表明连接成功
二、简单的增删查改sql语句
2.1 传入参数
(1) 可以传入一个JavaBean
(2) 可以传入一个Map
(3) 可以传入多个参数,需使用@Param("ParamName") 修饰参数
2.2 Insert,Update,Delete 返回值
接口方法返回值可以使用 void 或 int,int返回值代表影响行数
2.3 Select 中使用@Results 处理映射
查询语句中,如何名称不一致,如何处理数据库字段映射到Java中的Bean呢?
(1) 可以使用sql 中的as 对查询字段改名,以下可以映射到User 的 name字段
@Select("select "1" as name from dual")
User testSqlConnent();
(2) 使用 @Results,有 @Result(property="Java Bean name", column="DB column name"), 例如:
@Select("select t_id, t_age, t_name " + "from sys_user " + "where t_id = #{id} ") @Results(id="userResults", value={ @Result(property="id", column="t_id"), @Result(property="age", column="t_age"), @Result(property="name", column="t_name"), })
User selectUserById(@Param("id") String id);
对于resultMap 可以给与一个id,其他方法可以根据该id 来重复使用这个resultMap。例如:
@Select("select t_id, t_age, t_name " + "from sys_user " + "where t_name = #{name} ") @ResultMap("userResults") User selectUserByName(@Param("name") String name);
2.4 注意一点,关于JavaBean 的构造器问题
我在测试的使用,为了方便,给JavaBean 添加了一个带参数的构造器。后面在测试resultMap 的映射时,发现把映射关系@Results 注释掉,返回的bean 还是有数据的;更改查询字段顺序时,出现 java.lang.NumberFormatException: For input string: "hello"的异常。经过测试,发现是bean 的构造器问题。并有以下整理:
(1) bean 只有一个有参的构造方法,MyBatis 调用该构造器(参数按顺序),此时@results 注解无效。并有查询结果个数跟构造器不一致时,报异常。
(2) bean 有多个构造方法,且没有 无参构造器,MyBatis 调用跟查询字段数量相同的构造器;若没有数量相同的构造器,则报异常。
(3) bean 有多个构造方法,且有 无参构造器, MyBatis 调用无参数造器。
(4) 综上,一般情况下,bean 不要定义有参的构造器;若需要,请再定义一个无参的构造器。
2.5 简单查询例子
/** * 测试连接 */ @Select("select 1 from dual") int testSqlConnent(); /** * 新增,参数是一个bean */ @Insert("insert into sys_user " + "(t_id, t_name, t_age) " + "values " + "(#{id}, #{name}, ${age}) ") int insertUser(User bean); /** * 新增,参数是一个Map */ @Insert("insert into sys_user " + "(t_id, t_name, t_age) " + "values " + "(#{id}, #{name}, ${age}) ") int insertUserByMap(Map<String, Object> map); /** * 新增,参数是多个值,需要使用@Param来修饰 * MyBatis 的参数使用的@Param的字符串,一般@Param的字符串与参数相同 */ @Insert("insert into sys_user " + "(t_id, t_name, t_age) " + "values " + "(#{id}, #{name}, ${age}) ") int insertUserByParam(@Param("id") String id, @Param("name") String name, @Param("age") int age); /** * 修改 */ @Update("update sys_user set " + "t_name = #{name}, " + "t_age = #{age} " + "where t_id = #{id} ") int updateUser(User bean); /** * 删除 */ @Delete("delete from sys_user " + "where t_id = #{id} ") int deleteUserById(@Param("id") String id); /** * 删除 */ @Delete("delete from sys_user ") int deleteUserAll(); /** * truncate 返回值为0 */ @Delete("truncate table sys_user ") void truncateUser(); /** * 查询bean * 映射关系@Results * @Result(property="java Bean name", column="DB column name"), */ @Select("select t_id, t_age, t_name " + "from sys_user " + "where t_id = #{id} ") @Results(id="userResults", value={ @Result(property="id", column="t_id"), @Result(property="age", column="t_age"), @Result(property="name", column="t_name", javaType = String.class), }) User selectUserById(@Param("id") String id); /** * 查询List */ @ResultMap("userResults") @Select("select t_id, t_name, t_age " + "from sys_user ") List<User> selectUser(); @Select("select count(*) from sys_user ") int selectCountUser();
三、MyBatis动态SQL
注解版下,使用动态SQL需要将sql语句包含在script标签里
<script></script>
3.1 if
通过判断动态拼接sql语句,一般用于判断查询条件
<if test=''>...</if>
3.2 choose
根据条件选择
<choose> <when test=''> ... </when> <when test=''> ... </when> <otherwise> ... </otherwise> </choose>
3.3 where,set
一般跟if 或choose 联合使用,这些标签或去掉多余的 关键字 或 符号。如
<where> <if test="id != null "> and t_id = #{id} </if> </where>
若id为null,则没有条件语句;若id不为 null,则条件语句为 where t_id = ?
<where> ... </where> <set> ... </set>
3.4 bind
绑定一个值,可应用到查询语句中
<bind name="" value="" />
3.5 foreach
循环,可对传入和集合进行遍历。一般用于批量更新和查询语句的 in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
(1) item:集合的元素,访问元素的Filed 使用 #{item.Filed}
(2) index: 下标,从0开始计数
(3) collection:传入的集合参数
(4) open:以什么开始
(5) separator:以什么作为分隔符
(6) close:以什么结束
例如 传入的list 是一个 List<String>: ["a","b","c"],则上面的 foreach 结果是: ("a", "b", "c")
3.6 动态SQL例子
/** * if 对内容进行判断 * 在注解方法中,若要使用MyBatis的动态SQL,需要编写在<script></script>标签内 * 在 <script></script>内使用特殊符号,则使用java的转义字符,如 双引号 "" 使用"" 代替 * concat函数:mysql拼接字符串的函数 */ @Select("<script>" + "select t_id, t_name, t_age " + "from sys_user " + "<where> " + " <if test='id != null and id != ""'> " + " and t_id = #{id} " + " </if> " + " <if test='name != null and name != ""'> " + " and t_name like CONCAT('%', #{name}, '%') " + " </if> " + "</where> " + "</script> ") @Results(id="userResults", value={ @Result(property="id", column="t_id"), @Result(property="name", column="t_name"), @Result(property="age", column="t_age"), }) List<User> selectUserWithIf(User user); /** * choose when otherwise 类似Java的Switch,选择某一项 * when...when...otherwise... == if... if...else... */ @Select("<script>" + "select t_id, t_name, t_age " + "from sys_user " + "<where> " + " <choose> " + " <when test='id != null and id != ""'> " + " and t_id = #{id} " + " </when> " + " <otherwise test='name != null and name != ""'> " + " and t_name like CONCAT('%', #{name}, '%') " + " </otherwise> " + " </choose> " + "</where> " + "</script> ") @ResultMap("userResults") List<User> selectUserWithChoose(User user); /** * set 动态更新语句,类似<where> */ @Update("<script> " + "update sys_user " + "<set> " + " <if test='name != null'> t_name=#{name}, </if> " + " <if test='age != null'> t_age=#{age}, </if> " + "</set> " + "where t_id = #{id} " + "</script> ") int updateUserWithSet(User user); /** * foreach 遍历一个集合,常用于批量更新和条件语句中的 IN * foreach 批量更新 */ @Insert("<script> " + "insert into sys_user " + "(t_id, t_name, t_age) " + "values " + "<foreach collection='list' item='item' " + " index='index' separator=','> " + "(#{item.id}, #{item.name}, #{item.age}) " + "</foreach> " + "</script> ") int insertUserListWithForeach(List<User> list); /** * foreach 条件语句中的 IN */ @Select("<script>" + "select t_id, t_name, t_age " + "from sys_user " + "where t_name in " + " <foreach collection='list' item='item' index='index' " + " open='(' separator=',' close=')' > " + " #{item} " + " </foreach> " + "</script> ") @ResultMap("userResults") List<User> selectUserByINName(List<String> list); /** * bind 创建一个变量,绑定到上下文中 */ @Select("<script> " + "<bind name=\"lname\" value=\"'%' + name + '%'\" /> " + "select t_id, t_name, t_age " + "from sys_user " + "where t_name like #{lname} " + "</script> ") @ResultMap("userResults") List<User> selectUserWithBind(@Param("name") String name);