温馨提示:本文翻译自stackoverflow.com,查看原文请点击:java - Consolidating an One to Many relationship in Thymeleaf
java jpa spring-boot Thymeleaf

java - 巩固Thymeleaf的一对多关系

发布于 2020-04-13 12:56:53

我正在尝试使用Thymeleaf巩固一对多关系。让我们保持简单。我确实有一个烦恼,有一个疑问。

@Entity
public class Thiesis {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="thiesis")
    private Set<Question> questions = new HashSet<>();

    @ManyToOne(cascade=CascadeType.ALL)
    private Course course;

    @Temporal(TemporalType.TIMESTAMP)
    private Date createdAt;
}

和问题类:

@Entity
public class Question {
  @Id
  @GeneratedValue(strategy=GenerationType.AUTO)
  private Long id;
  private String question;
  @ManyToOne(cascade=CascadeType.ALL)
  private Thiesis thiesis;
}

这是保存thiesis的控制器:

@PostMapping("/teacher/{userId}")
public String addThiesis(@PathVariable Long userId, Thiesis thiesis,String name)
{
    thiesisService.save(thiesis, name);
    System.out.println(thiesis.getId());
    return "redirect:/teacher/" + userId.toString();
}

也是Thiesis的服务:

public Thiesis save(Thiesis thiesis, String name)
{
    Course course =courseRepo.findByName(name);
    if(course!=null) {
        thiesis.setCourse(course);
        for(Question question : thiesis.getQuestions()) {
            question.setThiesis(thiesis);
            questionService.save(question);
        }
        Date date = new Date();
        thiesis.setCreatedAt(new Timestamp(date.getTime()));

        return thiesisRepo.save(thiesis);

    }
    else {
        System.out.println("Couldn't save the thiesis");
        return null;
    }

胸腺

<form action="" th:object="${thiesis}"method="post">
    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" required/>
    <div class="form-group row" id="course_id">
        <label for="pyetja_1" class="col-12 col-sm-4 col-form-label">Pyetje:</label>
        <div class=" col-12 col-sm-8">  
            <input type="text" class="form-control" placeholder="Emri i Lendes..." th:field="*{course.name}" required/><br/>
        </div>                      
    </div>
</form>

但是结果没有进入数据库,并且作为响应,执行POST方法时收到403错误。可能问题出在我完成百里香中对象字段的方式上。我真的被困住了,我已经尝试了成千上万种方法,但是我没有处理它。任何帮助深表感谢。

查看更多

提问者
dprozz122
被浏览
93
Shpend Palushi 2020-02-03 07:00

从我从您的命名约定中可以看到和理解的内容来看,可能您是在将Mappings弄糟了。在这种情况下应该发生这种情况。发布的代码还应该包括@GetMapping,但是无论如何都要确保@GetMapping指向该视图,并且@PostMapping从该视图中获取您所引用的指定路径中的信息。