java mybatis 如何用GROUP BY多个字段 查询的时候,把非group by指定的字段生成一个list,举例一个java示例
时间: 2024-02-28 08:52:17 浏览: 112
可以使用MyBatis的ResultMap来实现这个需求。
假设有一个表student,包含字段id、name、age、gender。现在需要按照name和age分组,并且需要把每组中的id和gender字段组成一个List返回。
SQL语句如下:
```sql
SELECT name, age, GROUP_CONCAT(id) AS ids, GROUP_CONCAT(gender) AS genders
FROM student
GROUP BY name, age
```
其中GROUP_CONCAT是MySQL的函数,用于将分组中的多个值组合成一个字符串。在MyBatis中,可以使用ResultMap将结果映射为Java对象。
Java对象的定义:
```java
public class StudentGroup {
private String name;
private int age;
private List<Integer> ids;
private List<String> genders;
// getter和setter方法
}
```
ResultMap的定义:
```xml
<resultMap id="studentGroupMap" type="com.example.StudentGroup">
<id property="name" column="name"/>
<id property="age" column="age"/>
<collection property="ids" ofType="java.lang.Integer" resultMap="idListMap"/>
<collection property="genders" ofType="java.lang.String" resultMap="genderListMap"/>
</resultMap>
<resultMap id="idListMap" type="java.lang.Integer" >
<result column="ids" />
</resultMap>
<resultMap id="genderListMap" type="java.lang.String" >
<result column="genders" />
</resultMap>
```
最后,在Mapper接口中定义方法:
```java
@ResultMap("studentGroupMap")
@Select("SELECT name, age, GROUP_CONCAT(id) AS ids, GROUP_CONCAT(gender) AS genders FROM student GROUP BY name, age")
List<StudentGroup> getStudentGroups();
```
调用该方法即可得到按照name和age分组的结果,其中ids和genders字段分别为id和gender组成的List。
阅读全文
相关推荐
















