首页 > 解决方案 > 连接表并返回数据以与 Spring JPA 做出反应

问题描述

我正在尝试在 Spring JPA 中加入两个实体,以便我可以在反应中访问数据。

我在 postgres 中有一个带有相应表的Eventand实体。Course

在反应中,我遍历数据库中的所有事件并将它们显示在每个事件的卡片上。事件表包含courseid正在播放该事件的位置。但我想在卡片上显示coursename而不是courseid.

我目前无权访问它,因此需要加入表格以便我可以访问它。

我从未在 Spring JPA 中使用过查询,并且努力创建一个来进行此连接。

我想要这样的 SQL 查询,

select * from event join course on course.courseid=event.course_id where eventid=5

eventid将从 react 传递到 Spring 的位置,以便在每个循环期间,它将获得正确的eventid并显示该coursename事件的对应项。

标签: spring-boothibernate

解决方案


执行:

import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity
public class Course {

    @Id
    @Column(name = "courseid")
    private Long id;

    @Column(name = "coursename")
    private String courseName;

    @OneToMany(mappedBy = "course")
    private List<Event> events;

    // ...
}
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Entity
public class Event {

    @Id
    @Column(name = "eventid")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "course_id")
    private Course course;

    // ...
}
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface EventRepository extends JpaRepository<Event, Long> {
}

用法:

import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {

    @Autowired
    private EventRepository eventRepository;

    @GetMapping
    public Map<String, ? extends Object> index(@RequestParam("id") final long id) {

        // find by eventid
        final Optional<Event> res = eventRepository.findById(id);

        res.ifPresent(e -> {
            // course name
            System.out.println(e.getCourse().getCourseName());
        });

        return res.map(e -> Map.of("id", e.getId(), "course", e.getCourse().getCourseName()))
            .orElse(Map.of());
    }
}

推荐阅读