gpt4 book ai didi

java - Spring:使用 POST 请求保存带有外键的对象

转载 作者:行者123 更新时间:2023-12-01 14:29:00 24 4
gpt4 key购买 nike

我对 Spring (REST) 有点陌生,我正在构建一个简单的 REST web 服务。我用的是 RestController映射 HTTP 请求。我使用这个简单的方法来接受一个 POST 请求:

@RequestMapping(value = "/grade/create", method = RequestMethod.POST)
public ResponseEntity<Grade> createGrade(@RequestBody Grade grade)
{
dao.createGrade(grade);

return new ResponseEntity<Grade>(grade, HttpStatus.OK);
}
dao在这种情况下是一个带有 @Repository 的类注解。一个请求应该是这样的:
{
"gradeType": "REGULAR",
"grade": "10",
"passed": 1,
"userId": 1,
"exam_id": 1,
"user_id": 3
}

问题是, Grade有 2 个外键,用于用户和考试。我希望能够只传递外部实体的 ID,让 Hibernate 处理其余的事情。但是,目前我得到这个作为回应:
{
"timestamp": 1484758525821,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.InvalidDataAccessResourceUsageException",
"message": "could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement",
"path": "/grade/create"
}

我该如何解决这个问题?我听说过 JpaRepository ,我可以用它来完成这个吗?

我的 Grade模态如下:
@Entity
@Table(name = "grades")
@NamedQueries(value = {
@NamedQuery(name = "Grade.get", query = "SELECT c FROM Grade c WHERE id = :id"),
@NamedQuery(name = "Grade.getAll", query = "SELECT c FROM Grade c"),
@NamedQuery(name = "Grade.getAllByUser", query = "SELECT g FROM Grade g INNER JOIN Exam e ON g.exam.id = e.id INNER JOIN Course c ON e.course.id = c.id WHERE g.user.id = :id"),

})
public class Grade {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

@Column(name = "type")
private String gradeType;

@Column(name = "grade")
private String grade;

@Column(name = "passed")
private int passed;

@JsonIgnore
@ManyToOne
@JoinColumn(name = "user_id")
private User user;

@ManyToOne
@JoinColumn(name = "exam_id")
private Exam exam;

private int examId;

private int userId;

public Grade(int id, String gradeType, String grade, int passed, User user, Exam exam)
{
setId(id);
setGradeType(gradeType);
setGrade(grade);
setPassed(passed);
setUser(user);
setExam(exam);
}

public Grade() {
}

还有我的仓库...
@Repository
public class GradeDao {

@PersistenceContext
private EntityManager em;

@Transactional
public List<Grade> getallGrades() {
return em.createNamedQuery("Grade.getAll", Grade.class)
.getResultList();
}

public List<Grade> getLimitedGradesByUser(int limit, int user_id) {
return em.createNamedQuery("Grade.getAllByUser", Grade.class)
.setParameter("id", user_id)
.setMaxResults(limit)
.getResultList();
}

@Transactional
public Grade getGrade(int id) {
return em.createNamedQuery("Grade.get", Grade.class).setParameter("id", id).getSingleResult();
}

@Transactional
public Grade createGrade(Grade grade) {
grade = em.merge(grade);
em.persist(grade);

return grade;
}
}

谢谢

最佳答案

How can I solve this? I've heard something about a JpaRepository, can I use that to accomplish this?



是的,您可以使用 JpaRepository 执行此操作。您可以开始添加 Interface public interface GradeRepository extends PagingAndSortingRepository<Grade, Long> ,同样适用于 UserExam那么当你 POST您的 Grade在您的 Controller 中(我建议使用 Service)
1.创建一个 new Grade() 2.使用 setters链接您的 UserExam来自 @Autowire -ing 你的 UserRepositoryExamRepository并调用 findById 3. 然后从您的 POST 中获取您的其他字段使用 setters 4.调用 .save(grade)来自您的 @Autowired GradeRepository
请注意 UserExam应该已经存在于 DB 中能够链接它们

此外,我强烈建议您永远不要通过 HTTP 传递直接实体。改为使用 DTOs并在您的 Grade json 永远不会通过 exam id .尝试按其他领域查找考试,而不是 table id (例如:findByName)

我用 JPA 和 Security 实现了一个功能齐全的 SpringBoot 应用程序,你可以看看 https://github.com/hodispk/internship

关于java - Spring:使用 POST 请求保存带有外键的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41725202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com