springboot整合JPA 多表关联 :一对多 多对多

发布时间:2023年12月24日

补充一下自定义SQL

?这是连表查询,可以任意查出字符,用Map接收

  @Test
    void test3() {
        JPAQueryFactory jpaQueryFactory = new JPAQueryFactory(em);
        QStudent student = QStudent.student;
        QMessage message = QMessage.message;
        //constructor(StuMesDto.class, student.id, student.name, student.grade, message.id, message.info)
        List<Map<Expression<?>, ?>> fetch = jpaQueryFactory.select(Projections.map(student.id, student.name, student.grade, message.id, message.info))
                .from(student)
                .innerJoin(message)
                .on(student.id.eq(message.stu_id))
                .orderBy(message.id.desc())
                .limit(1)
                .offset((1 - 1) * 1)
                .fetch();
        Object o = fetch.get(0).get(message.info);
        System.out.println(o);
    }

?这是连表查询,可以任意查出字符,用自定义对象接收

 @Test
    void test3() {
        JPAQueryFactory jpaQueryFactory = new JPAQueryFactory(em);
        QStudent student = QStudent.student;
        QMessage message = QMessage.message;
        //
        List<StuMesDto> fetch = jpaQueryFactory.select(Projections.constructor(StuMesDto.class, student.id, student.name, student.grade, message.id, message.info))
                .from(student)
                .innerJoin(message)
                .on(student.id.eq(message.stu_id))
                .orderBy(message.id.desc())
                .limit(1)
                .offset((1 - 1) * 1)
                .fetch();
        StuMesDto o = fetch.get(0);
        System.out.println(o);
    }
package com.jmj.springDataApp.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class StuMesDto {

    private Long sid;


    private String name;


    private Integer grade;

    private Long id;

    private String info;
}

文章来源:https://blog.csdn.net/qq_53374893/article/details/135178918
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。