Thymeleaf和JPA - 无法保存对象

时间:2017-11-13 18:17:54

标签: spring jpa thymeleaf

将Country对象设置为Pet对象时出现问题。

@Getter
@Setter
@EqualsAndHashCode
@NoArgsConstructor
@Entity
public class Country {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
}

我的宠物课

@Data
@Entity
public class Pet {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;

    @ManyToOne(fetch = FetchType.EAGER)
    private Country country;
    }

我试图以这种方式做到这一点(国家/地区是数据库中所有国家/地区的列表,我将此作为属性添加到模型中):

    <form th:object = "${pet}" th:action="@{/pet/}" method = "post">
    <select class="form-control" th:field="*{country}" >
        <option th:each="countryVal : ${countries}"
                th:value="${countryVal}"
                th:text="${countryVal.getName()}"
                >val
        </option>
    </select>
</form>

但是这不会将国家/地区对象保存到我的Pet对象中。 我必须这样做,我只将id保存到country对象:

<form th:object = "${pet}" th:action="@{/pet/}" method = "post">
    <select class="form-control" th:name="country.id" >
        <option th:each="countryVal : ${countries}"
                th:value="${countryVal.id}"
                th:text="${countryVal.getName()}"
                >val
        </option>
    </select>
</form>

有没有办法在Pet对象中将我的国家/地区对象从列表保存到国家/地区? 或者另一种方式。 这个代码是用country.id正确的方法将现有对象从数据库保存到我的Pet类中的对象吗?

1 个答案:

答案 0 :(得分:0)

th:field代码中缺少select。试试这个

<select class="form-control" th:field="*{country}"> // * is NOTa typo here
    <option th:each="countryVal : ${countries}"
            th:value="${countryVal.id}"
            th:text="${countryVal.getName()}"
            >val
    </option>
</select>

免责声明:这适用于Thymeleaf 3.

相关问题