MyBatis+PgSQL 实现数组类型字段的模糊查询功能
背景
项目列表,根据合作类型模糊查询,每个项目可以对应多个合作类型。
例如:根据合作类型=视频查询,可以查询出合作类型为“视频,图文” 和 “视频”的项目。
数据库定义一个数组类型的字段
用过PgSQL的朋友因该都知道,PgSQL可以直接定义数组类型的字段,
假如有一个project_info表,我们给表增加一个数组类型的字段cooperation_type
ALTER TABLE public.project_info ADD cooperation_type int[] NULL;
COMMENT ON COLUMN public.project_info.cooperation_type IS '合作类型';
表设计
存值格式为{ xx, xx},与下面xml里的集合遍历格式是有关联的
实体类
由于数据库字段是 int[]类型的,定义实体类的时候自然要定义成list
```java
// 合作类型
private List<Integer> cooperationType;
MyBatis Mapper.xml文件
<select id="queryListByCondition">
SELECT
*
FROM project_info
<where>
1=1
<if test="cooperationType != null and !cooperationType.isEmpty()">
AND
<foreach collection="cooperationType" item="item" open="'{" close="}'" separator=",">
${item}
</foreach>
&& (cooperation_type)
</if>
</where>
</select>
查询结果
输入2,可以查出所有包含2的