赞
踩
插件文档 https://mybatisplusjoin.com
插件Github仓库 https://github.com/yulichang/mybatis-plus-join
在pom中添加依赖
<dependency>
<groupId>com.github.yulichang</groupId>
<artifactId>mybatis-plus-join-boot-starter</artifactId>
<version>1.4.11</version>
</dependency>
将实体mapper有Mybatis plus的BaseMapper改成插件的 MPJBaseMapper
@Mapper
public interface UserMapper extends MPJBaseMapper<UserDO> {
}
查询 user 表全部字段address表的 city、address字段
public class SampleTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
MPJLambdaWrapper<User> wrapper = JoinWrappers.lambda(User.class)
.selectAll(User.class)//查询user表全部字段
.select(Address::getCity, Address::getAddress)
.leftJoin(Address.class, Address::getUserId, User::getId);
List<UserDTO> userList = userMapper.selectJoinList(UserDTO.class, wrapper);
}
}
生成的sql
SELECT t.id,t.name,t.age,t.email,t2.city,t2.address FROM user t LEFT JOIN address t1 ON t1.user_id = t.id
通过以上几个简单的步骤,我们就实现了 User 表的连表功能,甚至连 XML 文件都不用编写!
从以上步骤中,我们可以看到集成MyBatis-Plus-Join非常的简单,只需要引入 starter 工程即可。
但 MyBatis-Plus-Join 的强大远不止这些功能,全部功能请参考 插件文档 https://mybatisplusjoin.com
mybatis plus join插件支持mybatis plus原生的插件
public class SampleTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
MPJLambdaWrapper<User> wrapper = JoinWrappers.lambda(User.class)
.selectAll(User.class)//查询user表全部字段
.select(Address::getCity, Address::getAddress)
.leftJoin(Address.class, Address::getUserId, User::getId);
//分页查询 只需调用selectJoinPage方法,传入Mybatis Plus的page对象就行了
Page<UserDTO> page = userMapper.selectJoinPage(new Page<>(1, 10), UserDTO.class, wrapper);
}
}
对应sql
我这用的是Mysql,会添加 Limit, 分页插件会更具不同数据库拼接不同的分页方言
SELECT t.id,t.name,t.age,t.email,t2.city,t2.address FROM user t LEFT JOIN address t1 ON t1.user_id = t.id LIMIT ?
对多查询也很方便,只需调用selectCollection就行了, 对多查询需要List集合作为映射字段类型
public class SampleTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
MPJLambdaWrapper<User> wrapper = JoinWrappers.lambda(User.class)
.selectCollection(AddressDO.class, UserDTO::getAddressList)
.leftJoin(Address.class, Address::getUserId, User::getId);
List<UserDTO> list= userMapper.selectJoinList(UserDTO.class, wrapper);
}
}
一对一查询和对多查询用法一模一样, 把selectCollection换成selectAssociation就行了, 映射字段就不能是集合了,改成对应的实体类或DTO类
public class SampleTest {
@Autowired
private UserMapper userMapper;
@Test
public void testSelect() {
MPJLambdaWrapper<User> wrapper = JoinWrappers.lambda(User.class)
.selectAssociation(AddressDO.class, UserDTO::getAddressDto)
.leftJoin(Address.class, Address::getUserId, User::getId);
List<UserDTO> list= userMapper.selectJoinList(UserDTO.class, wrapper);
}
}
通过以上几个简单的步骤,我们就实现了 User 表的一对一和一对多功能,甚至连 XML 文件都不用编写!
插件还支持指定字段映射,指定别名映射,嵌套映射等强大的功能, 全部功能请参考 插件文档 https://mybatisplusjoin.com
无侵入:只做增强不做改变,引入它不会对现有工程产生影响,如丝般顺滑
无感引入, 支持MP风格的查询, 您会MP就会MPJ, 无需额外的学习成本
兼容MP的别名、逻辑删除、枚举列、TypeHandle列等特性
全部功能请参考 插件文档 https://mybatisplusjoin.com
如果您在使用过程中有任何问题或疑问,欢迎提issue或通过Github或Gitee咨询作者
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。