JPA多表关联查询用法

简单示例分析

现在有学生表(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()]));
        };
    }
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇