springboot中使用mybatis注解配置详解

一:传参方式

1.使用参数顺序
// 接口
public interface UserMapper {
     
    List<User> select(String name,Integer age);
}

xml文件时:

<select id="select" resultType="model.User">
    select * from `user` where name = #{arg0} and age =#{arg1}
select>
// or
<select id="select" resultType="model.User">
    select * from `user` where name = #{param1} and age =#{param2}
select>
2.使用@Param
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);

@Param中定义的name对应了SQL中的#{name},age对应了SQL中的#{age}。

3.使用Map

对于insert语句中需要的参数只需要在map中添加同名的key值就可以:

Map<String, Object> map = new HashMap<>();
map.put("name", "CCC");
map.put("age", 40);
userMapper.insertByMap(map);

通过**Map**对象来作为传递参数的容器:

@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER})")
int insertByMap(Map<String, Object> map);

由于map的value为Object,即insert语句中需指定参数的数据类型:jdbcType=INTEGER等。

4.使用javaBean
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insertByUser(User user);

#{name}、#{age}就分别对应了User对象中的name和age属性。

5.总结:

xml或注解形式:

当只有一个参数时:使用arg0,param1获得参数是一直有效的。
参数是基本类型:变量名可以随便写,#{id},#{ids},#{123},#{xxgdsgdg},等都可以获得到参数。
参数是javabean:填写Javabean中的属性名
参数是数组:使用array获得参数,再用foreach循环
参数是List:使用list或collection获得参数,再用foreach循环
参数是Set:使用collection获得参数,再用foreach循环

当有多个参数时:
使用argN、paramN或@param定位到某个参数,再灵活使用ognl就ok了。比如#{user.name}、#{users[0].name}

6.注意
void deleteUserRole(long userId,long[] roleIds);

多个参数时:roleIds是数组,但foreach不能用array。使用参数顺序或@Param。

<foreach collection="arg1" open="(" close=")" separator=" or " item="value">
    #{value}
foreach>

二:映射语句

1.insert
<insert id="insert"  parameterType="User" useGeneratedKeys="true" keyProperty="id">
    
    insert into user (username,address,email) values (#{username},#{address},#{email})
insert>
@Insert("insert into user (username,address,email) values (#{username},#{address},#{email})")
@Options(useGeneratedKeys = true, keyProperty = "id") 
public int insert(User user) throws Exception;

使用@Options注解的userGeneratedKeys 和keyProperty属性,让数据库auto_increment生成的主键值,赋值到keyProperty标记的属性id中;

还有另外一种方法可以获取主键:

<insert id="insert"  parameterType="User" >
    
    <selectKey keyProperty="id" order="AFTER" resultType="java.lang.Integer">
           select last_insert_id()
    selectKey>
    insert into user (username,address,email) values (#{username},#{address},#{email})
insert>
@Insert("insert into user (username,address,email) values (#{username},#{address},#{email})")
@SelectKey(statement="select last_insert_id()",keyProperty="id", resultType=int.class, before=true)
public int insert(User user) throws Exception;
2.select、update、delete
@Select("select * from user where id=#{id}")
public User selectById(int id) throws Exception;

@Update("update user set username=#{username},address=#{address},email=#{email} where id=#{id}")
public int update(User user) throws Exception;

@Delete("delete from user where id=#{id}")
public int delete(int id) throws Exception;

三:结果映射

Mybatis主要提供这些映射注解:
@Results 用于填写结果集的多个字段的映射关系.
@Result 用于填写结果集的单个字段的映射关系.
@ResultMap 根据ID关联XML里面.

在xml配置文件中,将查询结果和JavaBean属性映射起来的标签是。对应的是@Results注解。

@Results({
      @Result(id = true, column = "id", property = "id"),
        @Result(column = "username", property = "user_name"),
        @Result(column = "city", property = "city") })
@Select("select * from user")
public List<User> selectAll() throws Exception;

@Results({
      @Result(id = true, column = "id", property = "id"),
        @Result(column = "username", property = "user_name"),
        @Result(column = "city", property = "city") })
@Select("select * from user where id=#{id}")
public User selectById(int id) throws Exception;

上面的@Results注解重复使用了。要想使用可以复用的映射器,那么就使用@ResultMap注解。该注解依赖一个xml配置文件。 在接口文件同目录下新建一个userMapper.xml文件,并定义一个名为userMap的resultMap。

<mapper namespace="mapper.UserMapper">
    
    <resultMap id="userMap" type="pojo.User">
        <id column="id" property="id" jdbcType="INTEGER" />
        <result property="user_name" column="username">result>
        <result property="city" column="city">result>
    resultMap>
mapper>

在userMapper.java中,使用@ResultMap引用名为userMap的resultMap,实现复用。

@ResultMap("mapper.UserMapper.userMap") 
@Select("select * from user where id=#{id}")  
public User selectById(int id) throws Exception;

@Select("select * from user")  
@ResultMap("mapper.UserMapper.userMap")  
public List<User> selectAll() throws Exception;

为了方便演示和免除手工编写映射关系的烦恼,这里提供了一个快速生成映射结果集的方法,具体内容如下:

	/**
     * 1.用于获取结果集的映射关系
     */
    public static String getResultsStr(Class origin) {
     
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("@Results({\n");
        for (Field field : origin.getDeclaredFields()) {
     
            String property = field.getName();
            //映射关系:对象属性(驼峰)->数据库字段(下划线)
            String column = new PropertyNamingStrategy.SnakeCaseStrategy().translate(field.getName()).toUpperCase();
            stringBuilder.append(String.format("@Result(property = \"%s\", column = \"%s\"),\n", property, column));
        }
        stringBuilder.append("})");
        return stringBuilder.toString();
    }

四:关联关系

1.一对一关系

MyBatis提供了@One注解来配合@Result注解,从而实现一对一关联查询数据的加载。
如:一个用户对应一个账户,User对象中声明Account属性;

@Results({
      @Result(id = true, column = "id", property = "id"),
        @Result(column = "username", property = "user_name"),
        @Result(column = "city", property = "city"),
        @Result(column = "account_id", property = "account",one = @One(select = "mapper.AccountMapper.selectById")) })
@Select("select * from user")
public List<User> selectAll() throws Exception;

在这里column = "account_id"是mapper.AccountMapper.selectById方法传递的参数,property = "account"是User对象的account属性。如果@One中SELECT查询返回了多行结果,则会抛出TooManyResultsException异常。

如果结果映射使用的是xml文件,那么可以association 来配置映射

<mapper namespace="mapper.UserMapper">
    
    <resultMap id="userMapWithAccount" type="pojo.User">
        <id column="id" property="id" jdbcType="INTEGER" />
        <result property="user_name" column="username">result>
        <result property="city" column="city">result>
        <association property="account" javaType="Account" column="account_id" 
            select="mapper.AccountMapper.selectById" />
    resultMap>
mapper>

接口如下:

@Select("select * from user")
@ResultMap("mapper.UserMapper.userMapWithAccount")
public List<User> selectAll() throws Exception;
2.一对多关系

MyBatis提供了@Many注解来配合@Result注解,从而实现一对多关联查询数据的加载。
如:一个讲师对应多个课程,在Tutor里声明courseList属性。

public interface TutorMapper
{
     
	@Results({
     
	        @Result(id = true, column = "course_id", property = "courseId"),
	        @Result(column = "name", property = "name"),
	        @Result(column = "description", property = "description"),
	        @Result(column = "start_date" property = "startDate"),
	        @Result(column = "end_date" property = "endDate")
	    })
    @Select("select * from courses where tutor_id=#{tutorId}")
    List<Course> findCoursesByTutorId(int tutorId);

    @Results({
     
        @Result(id = true, column = "tutor_id", property = "tutorId"),
        @Result(column = "tutor_name", property = "name"),
        @Result(column = "email", property = "email"),
        @Result(property = "courses", column = "tutor_id",
        many = @Many(select = "mappers.TutorMapper.findCoursesByTutorId"))
    })
    @Select("SELECT tutor_id, name as tutor_name, email, addr_id FROM tutors where tutor_id=#{tutorId}")
    Tutor findTutorById(int tutorId);
}

采用配置xml中配置resultMaps的方式,可以用collection来配置映射

<mapper namespace="mappers.TutorMapper">
    <resultMap type="Course" id="CourseResult">
        <id column="course_id" property="courseId" />
        <result column="name" property="name" />
        <result column="description" property="description" />
        <result column="start_date" property="startDate" />
        <result column="end_date" property="endDate" />
    resultMap>
    <resultMap type="Tutor" id="TutorResult">
        <id column="tutor_id" property="tutorId" />
        <result column="tutor_name" property="name" />
        <result column="email" property="email" />
        <collection property="courses" resultMap="CourseResult" />
    resultMap>
mapper>

接口可写成下面:

public interface TutorMapper
{
     
    @Select("SELECT * FROM TUTORS T LEFT JOIN ADDRESSES A ON T.ADDR_ID=A.ADDR_ID LEFT OUTER JOIN COURSES C ON T.TUTOR_ID=C.TUTOR_ID WHERE T.TUTOR_ID=#{tutorId}")
    @ResultMap("mappers.TutorMapper.TutorResult")
    Tutor selectTutorById(int tutorId);
}

五:动态SQL

MyBatis提供了各种注解如@InsertProvider,@UpdateProvider,@DeleteProvider和@SelectProvider,来帮助构建动态SQL语句,然后让MyBatis执行这些SQL语句。

以@SelectProvider 为例,主要包含两个注解属性,其中type表示工具类,method 表示工具类的某个方法,用于返回具体的SQL。

@Mapper
public interface UserMapper {
     
    @SelectProvider(type = UserSqlProvider.class, method = "list222")
    List<User> list2();
}

工具类代码:

public class UserSqlProvider {
     
    public String list222() {
     
        return "select * from t_user ;
    }

六:案例

1.引入依赖
<dependencies>
        <dependency> 
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency> 
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.3.1version>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
    dependencies>
2.添加配置
spring:
  datasource:
    #连接MySQL
    url: jdbc:mysql://localhost:3306/socks?useSSL=false
    username: root
    password: root
    driver-class-name: com.mysql.jdbc.Driver

mybatis:
  configuration:
   #配置项:开启下划线到驼峰的自动转换. 作用:将数据库字段根据驼峰规则自动注入到对象属性。
   map-underscore-to-camel-case: true

logging:
  level:
   #打印SQL信息
   com.hehe.mapper: debug
3.数据层代码
3.1 UserMapper接口:用于数据查询
@Mapper
public interface UserMapper {
     
    /**
     * 方式1:使用注解编写SQL。
     */
    @Select("select * from t_user")
    List<User> list();

    /**
     * 方式2:使用注解指定某个工具类的方法来动态编写SQL.
     */
    @SelectProvider(type = UserSqlProvider.class, method = "listByUsername")
    List<User> listByUsername(String username);

    /**
     * 延伸:上述两种方式都可以附加@Results注解来指定结果集的映射关系.
     *
     * PS:如果符合下划线转驼峰的匹配项可以直接省略不写。
     */
    @Results({
     
            @Result(property = "userId", column = "USER_ID"),
            @Result(property = "username", column = "USERNAME"),
            @Result(property = "password", column = "PASSWORD"),
            @Result(property = "mobileNum", column = "PHONE_NUM")
    })
    @Select("select * from t_user")
    List<User> listSample();

    /**
     * 延伸:无论什么方式,如果涉及多个参数,则必须加上@Param注解,否则无法使用EL表达式获取参数。
     */
    @Select("select * from t_user where username like #{username} and password like #{password}")
    User get(@Param("username") String username, @Param("password") String password);

    @SelectProvider(type = UserSqlProvider.class, method = "getBadUser")
    User getBadUser(@Param("username") String username, @Param("password") String password);

}
3.2 UserSqlProvider类:用于生成SQL的工具类
/**
 * 主要用途:根据复杂的业务需求来动态生成SQL.
 * 

* 目标:使用Java工具类来替代传统的XML文件.(例如:UserSqlProvider.java <-- UserMapper.xml) */ public class UserSqlProvider { /** * 方式1:在工具类的方法里,可以自己手工编写SQL。 */ public String listByUsername(String username) { return "select * from t_user where username =#{username}"; } /** * 方式2:也可以根据官方提供的API来编写动态SQL。 */ public String getBadUser(@Param("username") String username, @Param("password") String password) { return new SQL() { { SELECT("*"); FROM("t_user"); if (username != null && password != null) { WHERE("username like #{username} and password like #{password}"); } else { WHERE("1=2"); } }}.toString(); } }

4.实体类User
public class User {
     
    private String userId;
    private String username;
    private String password;
    private String mobileNum;
    //Getters & Setters
}

后记

官方文档:http://www.mybatis.org/mybatis-3/zh/java-api.html
使用注解配置Mapper:https://blog.csdn.net/soonfly/article/details/67640653
SpringBoot 快速整合Mybatis:https://zhuanlan.zhihu.com/p/31015559
Spring Boot中使用MyBatis注解配置详解:http://blog.didispace.com/mybatisinfo/

你可能感兴趣的:(javaEE知识,mybatis)