简单示例分析
现在有学生表(student)和班级表(school_class),要求同时查询出学生姓名信息及对班级信息,可根据学生姓名或班级姓名查询数据。
字段示例
学生表
字段名 说明 id 主键id student_name 学生姓名 class_id 班级id
班级表
字段名 说明 id 主键id class_name 班级名称
SQL实现
select s.student_name ,c.class_name from student s join school_class c on s.class_id = c.id where s.student_name like '%keywords%' or c.class_name like '%keywords%'
JPA 实现
学生实体类
@Data
@Entity
@Table(name="student")
public class StudentPO implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column
@GeneratedValue(generator = "generator")
@GenericGenerator(name = "generator", strategy = "uuid.hex")
private String id;
@Column
private String studentName;
@OneToOne
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name = "class_id", referencedColumnName = "id",insertable = false, updatable = false)
private SchoolClass schoolClass;
}
班级实体类
@Data
@Entity
@Table(name="school_class")
public class SchoolClass implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column
@GeneratedValue(generator = "generator")
@GenericGenerator(name = "generator", strategy = "uuid.hex")
private String id;
@Column
private String className;
}
构建高级查询
/**
* 根据关键字模糊匹配数据
* @param keywords
* @return
*/
public static Specification<StudentPO> keywordsLike(String keywords) {
if (StrUtil.isBlank(keywords)) {
return null;
}
return (root, query, cb) -> {
List<Predicate> conditionList = new ArrayList<>();
conditionList.add(cb.like(root.get("studentName"), "%" + keywords + "%"));
Join<StudentPO, SchoolClass> join = root.join("schoolClass", JoinType.INNER);
conditionList.add(cb.like(join.get("className"), "%" + keywords + "%"));
return cb.and(conditionList.toArray(new Predicate[conditionList.size()]));
};
}