【问题标题】:Thymeleaf and JPA - object saving isn't possibleThymeleaf 和 JPA - 无法保存对象
【发布时间】:2018-04-26 12:38:24
【问题描述】:

我在将 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>

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

<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>

有什么方法可以将我的国家/地区对象从列表保存到宠物对象中的国家/地区? 或者其他方式。 这个带有 country.id 的代码是否可以正确地将现有对象从数据库保存到我的 Pet 类中的对象?

【问题讨论】:

    标签: spring jpa thymeleaf


    【解决方案1】:

    您在select 标记中缺少th:field。试试这个

    <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。

    【讨论】:

    • 国家仍然为空。以你的方式。提交后我尝试在控制器中使用国家/地区,我得到 java.lang.NullPointerException: null
    • 我不知道你在说什么,但应该像我给你看的那样做。 th:field 在这里是强制性的。你最好检查一下你从哪里得到 NPE
    • 当我按照您的方式执行此操作时,数据库中有 pet 表中 country_id 列的空字段。
    • 你的countries有问题应该这样处理。
    • 好的,我明白了。谢谢。
    猜你喜欢
    • 2021-01-28
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2020-11-17
    • 2018-02-24
    • 2019-04-10
    相关资源
    最近更新 更多