mybatisplus多对一
时间: 2023-09-26 07:07:22 浏览: 59
MyBatis-Plus提供了方便的方式来实现多对一查询。根据引用中的描述,我们可以在对应的mapper.xml文件中使用resultMap、association和collection标签来定义多对一关系。
首先,我们需要在entity实体类中添加@ManyToOne注解,表示多对一的关系。例如,在一个学生实体类中,我们可以这样定义多对一关系:
```java
@ManyToOne
@JoinColumn(name = "department_id")
private Department department;
```
在mapper.xml文件中,我们可以使用resultMap标签来映射查询结果到实体类。在resultMap标签内部,我们可以使用association标签来定义多对一关系。例如:
```xml
<resultMap id="studentResultMap" type="com.example.Student">
<id property="id" column="id"/>
<result property="name" column="name"/>
<!-- 其他属性映射 -->
<association property="department" javaType="com.example.Department">
<id property="id" column="department_id"/>
<result property="name" column="department_name"/>
<!-- 其他属性映射 -->
</association>
</resultMap>
```
上述代码中,我们将department属性定义为一个association标签,指定了多对一关系的映射关系。
接下来,我们可以在查询语句中使用这个resultMap。例如,查询所有学生以及对应的部门信息:
```xml
<select id="findStudentsWithDepartment" resultMap="studentResultMap">
SELECT s.id, s.name, d.id as department_id, d.name as department_name
FROM students s
LEFT JOIN departments d ON s.department_id = d.id
</select>
```
在上述查询语句中,我们使用了resultMap属性将查询结果映射到Student实体类,并且通过LEFT JOIN关联了departments表。
通过以上的配置,我们可以方便地实现多对一查询。这样,查询结果中的每个学生对象都会包含对应的部门对象。
参考资料:
项目中用到了MyBatis-Plus,使用一对多、多对一查询会方便很多,大致写法和MyBatis一样,在对应的mapper.xml里使用resultMap、association和collection标签
主要介绍了MyBatis-Plus自定义Sql实现多表查询的示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值
实体类加@TableField(exist = false)//表示该字段不是数据库中字段但是必须要使用的 private Dep dep;
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)