MyBatis和JPA一样,也是一款优秀的持久层框架,它支持定制化SQL、存储过程,以及高级映射。它可以使用简单的XML或注解来配置和映射原生信息,将接口和Java的POJOs ( Plain Old Java Objects,普通的Java对象)映射成数据库中的记录。
MyBatis 3提供的注解可以取代XML例如,使用注解@Select直接编写SQL完成数据查询; 使用高级注解@SelectProvider还可以编写动态SQL,以应对复杂的业务需求。
増加、删除、修改和查询是主要的业务操作,必须掌握这些基础注解的使用方法。MyBatis提供的操作数据的基础注解有以下4个。
下面来看看它们具体如何使用,见以下代码:
package com.itheima.mapper; import com.itheima.domain.User; import org.apache.ibatis.annotations.*; import org.springframework.data.domain.Page; import java.util.List; @Mapper public interface UserMapper { @Select("select * from user where id = #{id}") User queryById(@Param("id")int id); @Select("select * from user") List<User> queryAll(); @Insert({"insert into user(name,age) values(#{name},#{age})"}) int add(User user); @Delete("delete from user where id = #{id}") int delete(int id); @Update("update user set name = #{name},age = #{age} where id = #{id}") int updateById(User user); @Select("select * from user") Page<User> getUserList(); }
从上述代码可以看岀:首先要用@Mapper注解来标注类,把UserMapper这个DAO交给 Spring管理。这样Spring会自动生成一个实现类,不用再写UserMapper的映射文件了。最后使用基础的CRUD注解来添加要实现的功能。
MyBatis的映射注解用于建立实体和关系的映射。它有以下3个注解。
可以在查询SQL的基础上,指定返回的结果集的映射关系。其中,property表示实体对象的属性名,column表示对应的数据库字段名。使用方法见以下代码:
@Results({ @Result(property = "username",column = "USERNAME"), @Result(property = "password",column = "PASSWORD") }) @Select("select * from user ") List<User> list();
MyBatis 3.x版本主要提供了以下4个CRUD的高级注解。
高级注解主要用于编写动态SQL,这里以@SelectProvider为例,它主要包含两个注解属性, 其中,type表示工具类,method表示工具类的某个方法(用于返回具体的SQL )。以下代码可以构建动态SQL,实现查询功能:
package com.itheima.mapper; import com.itheima.domain.User; import com.itheima.util.UserSql; import org.apache.ibatis.annotations.*; import org.springframework.data.domain.Page; import java.util.List; @Mapper public interface UserMapper { @SelectProvider(type = UserSql.class,method = "listAll") List<User> listAllUsers(); }
package com.itheima.util; public class UserSql { public String listAll(){ return "SELECT * FROM user"; } }
(1)如果要查询所有的值,则基础CRUD的代码是:
@Select("select * from user") List<User> queryAll();
也可以用映射注解来一一映射,见以下代码:
@Select("select * from user") @Results({ @Result(property = "id",column = "id"), @Result(property = "name",column = "name"), @Result(property = "age",column = "age") }) List<User> listAll();
(2)用多个参数进行查询。
如果要用多个参数逬行查询,则必须加上注解@Param,否则无法使用EL表达式获取参数.
@Select("select * from user where name like #{name} and age like #{age}") User getUserByNameAndAge(@Param("name") String name, @Param("age") int age);
还可以根据官方提供的API来编写动态SQL
public static String getUser(@Param("name") String name, @Param("age") int age){ return new SQL(){{ SELECT("*"); FROM("user"); if (name != null && age != 0){ WHERE("name like #{name} and age like #{age}"); }else { WHERE("1=2"); } }}.toString(); }
(1)创建实体类
@Data public class User{ private int id; private String name; private int age; }
(2)实现实体和数据表的映射关系
实现实体和数据表的映射关系可以在Mapper类上添加注解@Mapper,见以下代码。建议以 后直接在入口类加@MapperScan(" com.itheima.mapper"),如果対每个 Mapper 都加注解则很麻烦
package com.itheima.mapper; import com.itheima.domain.User; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper public interface UserMapper { @Select("select * from user where id = #{id}") User queryById(@Param("id")int id); @Select("select * from user") List<User> queryAll(); @Insert({"insert into user(name,age) values(#{name},#{age})"}) int add(User user); @Delete("delete from user where id = #{id}") int delete(int id); @Update("update user set name = #{name},age = #{age} where id = #{id}") int updateById(User user); }
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.3.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.0.7.RELEASE</version> </dependency>
package com.itheima.config; import com.github.pagehelper.PageHelper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; @Configuration public class PageHelperConfig { @Bean public PageHelper pageHelper(){ PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("offsetAsPageNum","true"); properties.setProperty("rowBoundsWithCount","true"); properties.setProperty("reasonable","true"); pageHelper.setProperties(properties); return pageHelper; } }
代码解释如下。
1.增加分页支持:
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.4.3</version> </dependency>
2.创建分页配置类:
package com.itheima.config; import com.github.pagehelper.PageHelper; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Properties; @Configuration public class PageHelperConfig { @Bean public PageHelper pageHelper(){ PageHelper pageHelper = new PageHelper(); Properties properties = new Properties(); properties.setProperty("offsetAsPageNum","true"); properties.setProperty("rowBoundsWithCount","true"); properties.setProperty("reasonable","true"); pageHelper.setProperties(properties); return pageHelper; } }
代码解释如下。
3.实现分页控制器:
package com.itheima.controller; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.itheima.domain.User; import com.itheima.mapper.UserMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import java.util.List; @Controller public class UserListController { @Autowired UserMapper userMapper; @RequestMapping("/pagelist") public String listCategory(Model model, @RequestParam(value = "start",defaultValue = "1") int start, @RequestParam(value = "size",defaultValue = "20") int size) { PageHelper.startPage(start, size,"id desc"); List<User> users = userMapper.queryAll(); PageInfo<User> page = new PageInfo<>(users); model.addAttribute("page", page); return "list"; } }
代码解释如下。
1.关注度
JPA在全球范围内的用户数最多,而MyBatis是国内互联网公司的主流选择
2.Hibernate 的优势
3.MyBatis的优势
4.简单总结
它们各自的缺点都可以依据各目更深入的技术方案来解决。所以,笔者的建议是: