<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
目前使用的ORM框架是Mybatis Plus,是Mybatis的增強框架,基礎的CRUD的方法都整合了,開發起來很是方便。但是專案中總是需要多表關聯查詢。
Mybatis的多表關聯有兩種
一、在Mapper中使用@Result @One @Many註解
二、在xml檔案中設定對應的resultMap和關聯標籤
使用起來很不方便。JPA倒是有多表關聯的註解實現,但是不想再引入另一個ORM框架。
目前的需求是增強現有的查詢,使用簡單的註解即可實現多表關聯。
GitHub:https://github.com/sushengbuyu/mybatis-mapping-demo
實現該功能總共需要四個檔案
兩個自定義註解,一個虛擬Mapper,一個切面處理類
原始碼
自定義對映註解,標註需要對映處理的欄位
import java.lang.annotation.*; /** * @author victor * @desc 自定義多表關聯對映註解 * @date 2022/5/23 */ @Documented @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface MapTo { /** * 對映目標 */ Class<?> targetClass(); /** * 執行SQL */ String sql(); /** * 巢狀處理 * 為true時,如果對映的物件類中有對映欄位,也執行對映操作 */ boolean doDeep() default false; }
自定義對映處理註解,標註需要執行對映的方法
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author victor * @desc 標註該需要執行對映處理的方法 * @date 2022/5/23 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface DoMap { /** * 需要處理對映的類 * @return Class */ Class<?> targetClass(); /** * spel表示式 * 預設為空 * @return String */ String spel() default ""; }
虛擬Mapper,用來執行自定義SQL
import java.util.List; import java.util.Map; /** * @author victor * @desc 虛擬Mapper * @date 2022/5/23 */ @Mapper public interface IDualMapper { /** * 執行自定義SQL * @param sql sql * @return List<Map<String, Object>> */ List<Map<String, Object>> executeSql(String sql); }
使用者自行實現DualMapper,解除mybatis強依賴
package sushengbuyu.maptodemo.sys.mapper; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import sushengbuyu.maptodemo.aop.IDualMapper; import java.util.List; import java.util.Map; /** * @author victor * @desc 虛擬Mapper * @date 2022/5/23 */ @Mapper public interface DualMapper extends IDualMapper { /** * 執行自定義SQL * @param sql sql * @return List<Map<String, Object>> */ @Select("${sql}") List<Map<String, Object>> executeSql(@Param("sql") String sql); }
切面處理類,核心程式碼,執行對映操作
package sushengbuyu.maptodemo.aop; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.util.ClassUtil; import cn.hutool.core.util.ReUtil; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.annotation.PostConstruct; import java.lang.reflect.Field; import java.util.*; import java.util.stream.Collectors; /** * @author victor * @desc 自定義關聯對映切面 * @date 2022/5/23 */ @Component @Aspect public class DoMapAspect { private final static Logger log = LoggerFactory.getLogger(DoMapAspect.class); /** * 儲存MapTo對映關係 * key 對映欄位所在類 * value 對映欄位集合 */ private static final Map<Class<?>, Set<String>> MAPPING = new HashMap<>(8); private final IDualMapper dualMapper; public DoMapAspect(DualMapper dualMapper) { this.dualMapper = dualMapper; } /** * 初始化對映關係 * 掃描指定包下所有類,找出帶有MapTo註解的欄位 * 儲存對映資料 */ @PostConstruct public void initMap() { // 初始化所有MapTo物件 // 掃描所有類 Set<Class<?>> classes = ClassUtil.scanPackage("sushengbuyu.maptodemo"); int totalField = 0; // 找出使用MapTo註解的物件 for (Class<?> c : classes) { Field[] fields = c.getDeclaredFields(); for (Field f : fields) { if (null != f.getAnnotation(MapTo.class)){ log.info("找到需要對映的欄位: 類名:{} - 欄位名:{}", c.getName(), f.getName()); // 儲存對映關係 Set<String> set; if (MAPPING.containsKey(c)) { set = MAPPING.get(c); } else { set = new HashSet<>(); } set.add(f.getName()); MAPPING.put(c, set); totalField++; } } } log.info("總計{}個對映類,{}個對映欄位", MAPPING.size(), totalField); } /** * 切點 * @param doMap 執行對映註解 */ @Pointcut("@annotation(doMap)") public void point(DoMap doMap){} /** * 處理關聯對映 * @param point 切點 * @param doMap 對映處理設定 * @return Object * @throws Throwable 異常 */ @Around(value = "@annotation(doMap)") public Object doMap(ProceedingJoinPoint point, DoMap doMap) throws Throwable { // 執行切面方法 Object obj = point.proceed(); try { Object relObj = obj; if (StringUtils.hasLength(doMap.spel())) { // 如果使用了SPEL表示式,則從返回值中獲取處理物件 ExpressionParser parser = new SpelExpressionParser(); Expression expression = parser.parseExpression(doMap.spel()); relObj = expression.getValue(obj); } // 獲取對映類 Class<?> c = doMap.targetClass(); // 對映處理 doMapping(c, relObj); } catch (Exception e) { log.error("對映異常", e); } log.info("返回物件:{}", obj); return obj; } private void doMapping(Class<?> c, Object obj) throws Exception { if (obj instanceof Collection) { // 集合 Collection<?> co = (Collection<?>) obj; for (Object o : co) { mapping(c, o); } } else { // 單個物件 mapping(c, obj); } } private void mapping(Class<?> c, Object obj) throws Exception { // 判斷是否有對映關係 if (MAPPING.containsKey(c)) { log.info("處理對映類:{}", c.getName()); // 從快取中獲取對映欄位名稱 Set<String> filedNames = MAPPING.get(c); for (String fieldName : filedNames) { Field f = c.getDeclaredField(fieldName); log.info("處理對映欄位:{}", f.getName()); // 獲取對映註解 MapTo mapTo = f.getAnnotation(MapTo.class); log.info("對映設定:{}", mapTo); // 設定私有欄位存取許可權 f.setAccessible(true); // 執行SQL String sql = mapTo.sql(); // 處理SQL變數 List<String> res = ReUtil.findAll("${(.*?)}", sql, 0); log.info("SQL變數:{}", res); for (String re : res) { Field ff = obj.getClass().getDeclaredField(re.substring(2, re.length()-1)); ff.setAccessible(true); Object o = ff.get(obj); sql = sql.replace(re, o.toString()); } log.info("最終SQL:{}", sql); List<Map<String, Object>> results = dualMapper.executeSql(sql); Object v = null; if (Collection.class.isAssignableFrom(f.getType())) { // 集合物件 if (results.size() > 0) { v = results.stream() .map(r -> mapToBean(r, mapTo.targetClass())) .collect(Collectors.toList()); } } else { // 單個物件 if (results.size() > 1) { log.error("預計返回一條資料,實際返回多條資料。執行SQL: {}", sql); } else if (results.size() == 1) { // 轉換結果,賦值 v = mapToBean(results.get(0), mapTo.targetClass()); } } if (v != null && mapTo.doDeep()) { doMapping(mapTo.targetClass(), v); } f.set(obj, v); } } } /** * Map物件轉Bean * @param map map * @param clazz bean * @return bean */ private Object mapToBean(Map<?, ?> map, Class<?> clazz) { try { return BeanUtil.fillBeanWithMap(map, clazz.newInstance(), true); } catch (InstantiationException | IllegalAccessException e) { log.error("範例化異常", e); return null; } } }
測試類
import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import java.io.Serializable; import java.util.List; import java.util.StringJoiner; /** * @author victor * @desc 系統使用者 * @date 2022/5/17 */ public class SysUser implements Serializable { private static final long serialVersionUID = 4855472141572371097L; @TableId(type = IdType.ASSIGN_ID) private Long id; /** * 登入使用者名稱 */ private String username; /** * 登入密碼 */ private String password; /** * 暱稱 */ private String nickName; @MapTo(targetClass = SysRole.class , doDeep = true , sql = "SELECT * FROM sys_role WHERE user_id=${id}") @TableField(exist = false) private SysRole sysRole; @MapTo(targetClass = SysRole.class , doDeep = true , sql = "SELECT * FROM sys_role WHERE user_id=${id}") @TableField(exist = false) private List<SysRole> roleList; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getNickName() { return nickName; } public void setNickName(String nickName) { this.nickName = nickName; } public SysRole getSysRole() { return sysRole; } public void setSysRole(SysRole sysRole) { this.sysRole = sysRole; } public List<SysRole> getRoleList() { return roleList; } public void setRoleList(List<SysRole> roleList) { this.roleList = roleList; } @Override public String toString() { return new StringJoiner(", ", SysUser.class.getSimpleName() + "[", "]") .add("id=" + id) .add("username='" + username + "'") .add("password='" + password + "'") .add("nickName='" + nickName + "'") .add("sysRole=" + sysRole) .add("roleList=" + roleList) .toString(); } }
package sushengbuyu.maptodemo.sys.po; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import sushengbuyu.maptodemo.aop.MapTo; import java.util.List; import java.util.StringJoiner; /** * @author victor * @desc 說明 * @date 2022/5/23 */ public class SysRole { @TableId private Long id; private Long userId; private String name; @MapTo(targetClass = SysPermission.class , sql = "SELECT p.* FROM sys_permission p " + "LEFT JOIN sys_role_permission rp ON p.id = rp.perm_id " + "WHERE rp.role_id = ${id}") @TableField(exist = false) private List<SysPermission> permissionList; public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public List<SysPermission> getPermissionList() { return permissionList; } public void setPermissionList(List<SysPermission> permissionList) { this.permissionList = permissionList; } @Override public String toString() { return new StringJoiner(", ", SysRole.class.getSimpleName() + "[", "]") .add("id=" + id) .add("userId=" + userId) .add("name='" + name + "'") .toString(); } }
package sushengbuyu.maptodemo.sys.po; import java.util.StringJoiner; /** * @author victor * @desc 說明 * @date 2022/5/25 */ public class SysPermission { private Long id; private String name; private Integer type; 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 Integer getType() { return type; } public void setType(Integer type) { this.type = type; } @Override public String toString() { return new StringJoiner(", ", SysPermission.class.getSimpleName() + "[", "]") .add("id=" + id) .add("name='" + name + "'") .add("type=" + type) .toString(); } }
測試用例就常見的三種, 查單個,查列表,查分頁
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; import java.io.Serializable; import java.util.List; /** * @author victor * @desc 說明 * @date 2022/5/17 */ @Service public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> { @DoMap(targetClass = SysUser.class) @Override public SysUser getById(Serializable id) { return super.getById(id); } @DoMap(targetClass = SysUser.class) public List<SysUser> listAll() { QueryWrapper<SysUser> wrapper = new QueryWrapper<>(); return baseMapper.selectList(wrapper); } /** * 從Page中取records作為處理物件 */ @DoMap(targetClass = SysUser.class, spel = "records") public Page<SysUser> page() { QueryWrapper<SysUser> wrapper = new QueryWrapper<>(); Page<SysUser> p = new Page<>(1, 10); return baseMapper.selectPage(p, wrapper); } }
import cn.hutool.json.JSONUtil; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; //@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class DoMapTests { @Autowired private SysUserService service; @Test void single() { System.out.println(JSONUtil.toJsonPrettyStr(service.getById(1))); } @Test void list() { System.out.println(JSONUtil.toJsonPrettyStr(service.listAll())); } @Test void page() { System.out.println(JSONUtil.toJsonPrettyStr(service.page())); } }
single
{ "nickName": "aa11", "roleList": [ { "permissionList": [ { "type": 0, "name": "add", "id": 1 }, { "type": 0, "name": "query", "id": 2 } ], "userId": 1, "name": "r1", "id": 11 }, { "permissionList": [ { "type": 0, "name": "del", "id": 3 } ], "userId": 1, "name": "r2", "id": 12 } ], "password": "123456", "id": 1, "username": "a1" }
list
[ { "nickName": "aa11", "roleList": [ { "permissionList": [ { "type": 0, "name": "add", "id": 1 }, { "type": 0, "name": "query", "id": 2 } ], "userId": 1, "name": "r1", "id": 11 }, { "permissionList": [ { "type": 0, "name": "del", "id": 3 } ], "userId": 1, "name": "r2", "id": 12 } ], "password": "123456", "id": 1, "username": "a1" }, { "sysRole": { "userId": 2, "name": "r3", "id": 13 }, "nickName": "aa22", "roleList": [ { "userId": 2, "name": "r3", "id": 13 } ], "password": "123456", "id": 2, "username": "a2" } ]
page
{ "optimizeCountSql": true, "records": [ { "nickName": "aa11", "roleList": [ { "permissionList": [ { "type": 0, "name": "add", "id": 1 }, { "type": 0, "name": "query", "id": 2 } ], "userId": 1, "name": "r1", "id": 11 }, { "permissionList": [ { "type": 0, "name": "del", "id": 3 } ], "userId": 1, "name": "r2", "id": 12 } ], "password": "123456", "id": 1, "username": "a1" }, { "sysRole": { "userId": 2, "name": "r3", "id": 13 }, "nickName": "aa22", "roleList": [ { "userId": 2, "name": "r3", "id": 13 } ], "password": "123456", "id": 2, "username": "a2" } ], "searchCount": true, "total": 0, "current": 1, "size": 10, "orders": [ ] }
到此這篇關於使用AOP+反射實現自定義Mybatis多表關聯的文章就介紹到這了,更多相關Mybatis多表關聯內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45