【问题标题】:Consolidating an One to Many relationship in Thymeleaf在 Thymeleaf 中巩固一对多关系
【发布时间】:2020-04-29 17:00:55
【问题描述】:

我正在尝试使用 Thymeleaf 巩固一对多的关系。让我们保持简单。我确实有一个 thiesis 一个 thiesis 有一些问题。

@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 错误。可能问题出在我在百里香中完成对象字段的方式上。我真的被困住了,我已经尝试了数千种方法,但我没有处理它。非常感谢任何帮助。

【问题讨论】:

  • 看起来像安全设置问题。如果有的话,你能附上一个堆栈跟踪和安全配置类吗?

标签: java spring-boot jpa thymeleaf


【解决方案1】:

根据我从您的命名约定中看到和理解的情况,您可能正在搞乱映射的情况。这应该发生在这些情况下。发布的代码还应包含@GetMapping,但无论如何要确保@GetMapping 指向该视图,并且@PostMapping 正在从您所指的指定路径中的该视图获取信息。

【讨论】:

  • 是的,这就是我所缺少的。 Get 指向其他地方,而帖子正在从另一条路径请求信息。它解决了我的问题。
猜你喜欢
  • 2012-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-28
  • 2017-05-30
  • 1970-01-01
  • 2015-06-21
  • 2017-11-10
相关资源
最近更新 更多