更新时间:2018年09月21日17时27分 来源:传智播客 浏览次数:
1.0 之前在Spring Boot中整合MyBatis时,采用了注解的配置方式,相信很多人还是比较喜欢这种优雅的方式的,也遇到不少问题,主要集中于针对各种场景下注解如何使用,下面就对几种常见的情况举例说明用法。
1.1 在做下面的示例之前,先准备一个整合好MyBatis的工程,可参见:使用Springboot整合mybatis
2.0 传参方式
下面通过几种不同传参方式来实现前文中实现的插入操作。
2.1使用@Param
使用这种最简单的传参方式,如下:
| 
	 1 
	2 
	 | 
	
	@Insert("insert into book (bookname) values #{bookname}")    Integer insertBook(@Param("bookname") String bookname); | 
	
这种方式很好理解,@Param 中定义的 bookname 对应了SQL中的 #{bookname}。
2.2 使用Map
| 
	 1 
	2 
	 | 
	
	@Insert("insert into book (bookname) values #{bookname, jdbcType =VARCHAR}")    Integer insertBookByMap(Map<String,Object> map ); | 
	
对于Insert语句中需要的参数,我们只需要在map中填入同名的内容即可,具体如下面代码所示:
| 
	 1 
	2 
	3 
	 | 
	
	Map<String, Object> map = new HashMap<>();       map.put("bookname", "CCC");       bookDaoMapper.insertBookByMap(map); | 
	
2.3 使用对象
除了Map对象,我们也可直接使用普通的Java对象来作为查询条件的传参,比如我们可以直接使用Book对象:
| 
	 1 
	2 
	 | 
	
	@Insert("insert into book (bookname) values #{bookname}")    Integer insertBookByPo(Book book); | 
	
3.0 增删改查
3.1 MyBatis针对不同的数据库操作分别提供了不同的注解来进行配置,在之前的示例中演示了@Insert,下面针对User表做一组最基本的增删改查作为示例:
| 
	 01 
	02 
	03 
	04 
	05 
	06 
	07 
	08 
	09 
	10 
	11 
	12 
	13 
	14 
	 | 
	
	public interface UserMapper {        @Select("SELECT * FROM user WHERE name = #{name}")        User findByName(@Param("name") String name);        @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")        int insert(@Param("name") String name, @Param("age") Integer age);        @Update("UPDATE user SET age=#{age} WHERE name=#{name}")        void update(User user);        @Delete("DELETE FROM user WHERE id =#{id}")        void delete(Long id);    } | 
	
在完成了一套增删改查后,单元测试来验证上面操作的正确性:省略。。。
3.2 返回结果的绑定
| 
	 1 
	2 
	3 
	4 
	5 
	6 
	 | 
	
	@Results({    @Result(property = "name", column = "name"),    @Result(property = "age", column = "age")})@Select("SELECT name, age FROM user")List<User> findAll(); | 
	
| 
	 1 
	2 
	3 
	4 
	5 
	 | 
	
	|-- user    |-- address    |-- carList        |-- car1        |-- car2 | 
	
| 
	 01 
	02 
	03 
	04 
	05 
	06 
	07 
	08 
	09 
	10 
	11 
	12 
	13 
	14 
	15 
	16 
	17 
	18 
	19 
	20 
	21 
	22 
	23 
	24 
	25 
	 | 
	
	//省略setter/getterpublic class Address {    private Long id;    private String province;    private String city;}public class Car {    private Long id;    private String color;    private String name;    //用户id    private Long userId;}public class User {    private Long id;    //地址信息,和用户是一对一的关系    private Address address;    //地址id    private Long addressId;    //用户拥有的车,和用户是一对多的关系    private List<Car> cars;} | 
	
| 
	 01 
	02 
	03 
	04 
	05 
	06 
	07 
	08 
	09 
	10 
	11 
	12 
	13 
	14 
	15 
	16 
	17 
	18 
	19 
	20 
	21 
	22 
	23 
	24 
	25 
	26 
	27 
	28 
	29 
	30 
	31 
	32 
	33 
	34 
	35 
	36 
	37 
	38 
	39 
	40 
	41 
	42 
	43 
	44 
	45 
	 | 
	
	CREATE TABLE IF NOT EXISTS `user` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `nick_name` varchar(50) DEFAULT NULL,  `address_id` int(11) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;CREATE TABLE IF NOT EXISTS `address` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `province` varchar(50) DEFAULT NULL,  `city` varchar(50) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;CREATE TABLE IF NOT EXISTS `car` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `color` varchar(50) DEFAULT NULL,  `name` varchar(50) DEFAULT NULL,  `user_id` int(11) DEFAULT NULL,  PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO    `user`VALUES    ('1', 'baby', '1'),    ('2', 'kingboy', '2'),    ('3', 'boy', '3'),    ('4', 'kingbaby', '4');INSERT INTO    `address`VALUES    ('1', '北京', '北京'),    ('2', '天津', '天津'),    ('3', '安徽', '宿州'),    ('4', '广东', '广州');INSERT INTO    `car`VALUES    ('1', 'green', '路虎', '1'),    ('2', 'white', '奔驰', '2'),    ('3', 'blue', '玛莎拉蒂', '4'),    ('4', 'yellow', '兰博基尼', '4'); | 
	
| 
	 1 
	2 
	3 
	4 
	5 
	6 
	7 
	 | 
	
	public interface AddressRepository {    /**     * 根据地址id查询地址     */    @Select("SELECT * FROM `address` WHERE id = #{id}")    Address findAddressById(Long id);} | 
	
| 
	 1 
	2 
	3 
	4 
	 | 
	
	public interface UserRepository {    @Select("SELECT * FROM `user` where id = #{id}")    User findUserWithAddress(Long id);} | 
	
| 
	 1 
	2 
	3 
	4 
	5 
	6 
	7 
	8 
	 | 
	
	public interface UserRepository {    @Select("SELECT * FROM `user` where id = #{id}")    @Results({            @Result(property = "address", column = "address_id",                    one = @One(select = "com.kingboy.repository.address.AddressRepository.findAddressById"))    })    User findUserWithAddress(Long id);} | 
	
| 
	 1 
	2 
	3 
	4 
	5 
	6 
	7 
	 | 
	
	public interface CarRepository {    /**     * 根据用户id查询所有的车     */    @Select("SELECT * FROM `car` WHERE user_id = #{userId}")    List<Car> findCarByUserId(Long userId);} | 
	
| 
	 1 
	2 
	3 
	4 
	 | 
	
	public interface UserRepository {    @Select("SELECT * FROM `user` where id = #{id}")    User findUserWithAddress(Long id);} | 
	
| 
	 01 
	02 
	03 
	04 
	05 
	06 
	07 
	08 
	09 
	10 
	11 
	 | 
	
	public interface UserRepository {    /**     * 查询带有车信息的用户===============演示一对多(关于多对多其实就是两个一对多组成)     */    @Select("SELECT * FROM `user` WHERE id = #{id}")    @Results({            @Result(property = "cars", column = "id",                    many = @Many(select = "com.kingboy.repository.car.CarRepository.findCarByUserId"))    })    User getUserWithCar(Long id);} |