博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring boot + mybatis实现一对一,一对多的样码之一种
阅读量:6290 次
发布时间:2019-06-22

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

实现的方法,有两种不同的风格,

一种是直接在接口里用注解实现,

另一种还是稳重的写xml,用resultmap来搞定。

经过几天的复习,

这个知识点差不多了。

参考URL:

http://blog.csdn.net/KingBoyWorld/article/details/78966789

建表语句:

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');
几个pojo,注意的是没有用外键关联,只是用了外键来对应,哪个表需要取外面的关联的,就要在POJO里建立对应的属性。

package opsstock.paic.com.cn.entity;public class Address {	private Long id;	private String province;	private String city;	public Long getId() {		return id;	}	public void setId(Long id) {		this.id = id;	}	public String getProvince() {		return province;	}	public void setProvince(String province) {		this.province = province;	}	public String getCity() {		return city;	}	public void setCity(String city) {		this.city = city;	}	@Override	public String toString() {		return "Address [id=" + id + ", province=" + province + ", city=" + city + "]";	}		}
package opsstock.paic.com.cn.entity;import java.util.List;public class User {	private Long id;	private String name;	private Address address;	private Long addressId;	private List
cars; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Long getAddressId() { return addressId; } public void setAddressId(Long addressId) { this.addressId = addressId; } public List
getCars() { return cars; } public void setCars(List
cars) { this.cars = cars; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", addressId=" + addressId + "]"; } }
package opsstock.paic.com.cn.entity;public class Car {	private Long id;	private String name;	private String color;	private Long userId;	public Long getId() {		return id;	}	public void setId(Long id) {		this.id = id;	}	public String getName() {		return name;	}	public void setName(String name) {		this.name = name;	}	public String getColor() {		return color;	}	public void setColor(String color) {		this.color = color;	}	public Long getUserId() {		return userId;	}	public void setUserId(Long userId) {		this.userId = userId;	}	@Override	public String toString() {		return "Car [id=" + id + ", name=" + name + ", color=" + color + ", userId=" + userId + "]";	}		}
相关mapper的写法,我总觉得,应该可以简化那个路径吧。

package opsstock.paic.com.cn.mapper;import org.apache.ibatis.annotations.Select;import opsstock.paic.com.cn.entity.Address;public interface AddressRepository {		@Select("SELECT * FROM `address` WHERE id = #{id}")	Address findAddressById(Long id);}
package opsstock.paic.com.cn.mapper;import java.util.List;import org.apache.ibatis.annotations.Select;import opsstock.paic.com.cn.entity.Car;public interface CarRepository {		@Select("SELECT * FROM `car` WHERE user_id = #{userId}")	List
findCarByUserId(Long userId);}
注意@One和@Many的注解哟

package opsstock.paic.com.cn.mapper;import org.apache.ibatis.annotations.Result;import org.apache.ibatis.annotations.Results;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.One;import org.apache.ibatis.annotations.Many;import opsstock.paic.com.cn.entity.User;public interface UserRepository {		@Select("SELECT * FROM `user` WHERE id=#{id}")	@Results({		@Result(property="address", column="address_id", 				one = @One(select = "opsstock.paic.com.cn.mapper.AddressRepository.findAddressById"))	})	User findUserWithAddress(Long id);			@Select("SELECT * FROM `user` WHERE id = #{id}")	@Results({		@Result(property="cars", column="id",				many = @Many(select="opsstock.paic.com.cn.mapper.CarRepository.findCarByUserId"))	})	User getUserWithCar(Long id);}
省掉service,直接测试:

package opsstock.paic.com.cn.controller;import javax.annotation.Resource;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import opsstock.paic.com.cn.entity.User;import opsstock.paic.com.cn.mapper.UserRepository;@RestController@RequestMapping(value="/user")public class UserController {		@Resource	UserRepository userRepository;		@GetMapping(value="/id/{id}/include/address")	public String findUserWithAddress(@PathVariable Long id) {		User userWithAddress = userRepository.findUserWithAddress(id);		return userWithAddress.getAddress().toString();	}			@GetMapping(value = "/id/{id}/include/car")    public String findUserWithCar(@PathVariable Long id) {        User user = userRepository.getUserWithCar(id);        return user.getCars().toString();    }	}
则输入网址:

http://localhost:8080/user/id/4/include/car

返回结果:

[Car [id=3, name=ÂêɯÀ­µÙ, color=blue, userId=4], Car [id=4, name=À¼²©»ùÄá, color=yellow, userId=4]]

(没有理会乱码之事)

你可能感兴趣的文章
Vue------第二天(计算属性、侦听器、绑定Class、绑定Style)
查看>>
dojo.mixin(混合进)、dojo.extend、dojo.declare
查看>>
Python 数据类型
查看>>
iOS--环信集成并修改头像和昵称(需要自己的服务器)
查看>>
PHP版微信权限验证配置,音频文件下载,FFmpeg转码,上传OSS和删除转存服务器本地文件...
查看>>
教程前言 - 回归宣言
查看>>
PHP 7.1是否支持操作符重载?
查看>>
Vue.js 中v-for和v-if一起使用,来判断select中的option为选中项
查看>>
Java中AES加密解密以及签名校验
查看>>
定义内部类 继承 AsyncTask 来实现异步网络请求
查看>>
VC中怎么读取.txt文件
查看>>
如何清理mac系统垃圾
查看>>
企业中最佳虚拟机软件应用程序—Parallels Deskto
查看>>
Nginx配置文件详细说明
查看>>
怎么用Navicat Premium图标编辑器创建表
查看>>
Spring配置文件(2)配置方式
查看>>
MariaDB/Mysql 批量插入 批量更新
查看>>
ItelliJ IDEA开发工具使用—创建一个web项目
查看>>
solr-4.10.4部署到tomcat6
查看>>
切片键(Shard Keys)
查看>>