spring-boot - 连接表并返回数据以与 Spring JPA 做出反应
问题描述
我正在尝试在 Spring JPA 中加入两个实体,以便我可以在反应中访问数据。
我在 postgres 中有一个带有相应表的Event
and实体。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
事件的对应项。
解决方案
执行:
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());
}
}
推荐阅读
- django - AttributeError:在 OneToOneField 模型字段上使用 F 函数时,“FloatField”对象没有属性“模型”错误
- c# - 我试图在统一 2d 中随机生成一些对象
- installation - 安装 ORO CRM /user/login 后抛出 404
- linux - 语法错误:无效的令牌运算符(错误令牌是“
- c# - 在没有 HttpContext 的情况下在“请求范围”和 HttpMessageHandler 之间共享数据
- jquery - 数据超过 1353 个字符时 Ajax 不起作用?ASP.NET MVC
- database - Heroku部署后清空我的数据库怎么办?
- android - Android 设备管理器在更新到 MacOS Big Sur 11.3 后无法启动
- iis - IIS 中的 .NET Remoting (*.rem) 404 错误仅适用于 v4.0
- javascript - 如何使用 GAS 中的 p5.js 库引用特定的 Google 表格单元格