java - 巩固 Thymeleaf 中的一对多关系

标签 java spring-boot jpa thymeleaf

我正在尝试使用 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 的 Controller :

@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;
    }

thymeleaf :

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

最佳答案

从我从你的命名约定中看到和理解的情况来看,你可能用映射搞乱了情况。在这些情况下应该会发生这种情况。发布的代码还应该包括@GetMapping,但无论如何请确保@GetMapping指向该 View ,并且@PostMapping正在从您所引用的指定路径中的该 View 获取信息。

关于java - 巩固 Thymeleaf 中的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59708872/

相关文章:

带有 Hibernate 的 SPRING JPA 更新所有实体实例,即使使用一个实体调用保存也是如此

java - 扫描仪被跳过

java - Android 保存多选 ListView 的状态

java - 将 Jackson 与泛型类型一起使用

java - 无法在 Spring Boot 项目中使用自定义 jar

java - 在java中使用thymeleaf html模板下载pdf文件时,css样式不可见

java - 几秒钟后启用“无选项”

java - 如何使用 spring jpa 编写查询来从数据库中获取与我们传递的字符串匹配的所有行?

java - Hibernate 实体更新现有行而不是使用 saveAndFlush 创建新行

java - 在数据源中创建不需要的空表