【问题标题】:Spring MVC/Thymeleaf - How to insert to two different tables using one input field?Spring MVC/Thymeleaf - 如何使用一个输入字段插入两个不同的表?
【发布时间】:2023-03-13 05:27:01
【问题描述】:

我有一个名字的输入字段:

<input th:field="*{fleet.firstName}" class="signup1" type="text" id="fname" name="fname" autofocus="" required=""/>

我有两个表/对象“舰队”和“服务”。如果 thymeleaf 只允许我在每个输入字段中使用一个对象,我该怎么做?

我尝试了两个输入 th:field,但没有成功。 喜欢:

<input th:field="*{fleet.firstName}" th:field="*{service.firstName}" class="signup1" type="text" id="fname" name="fname" autofocus="" required=""/>

【问题讨论】:

    标签: java spring spring-mvc thymeleaf


    【解决方案1】:

    我认为这是不可能的。您可以为 Thymeleaf 创建一个 DTO 对象,并结合您尝试在 Web 端查看的字段。然后,将其分离到服务层中的数据库表中。

    类似:

    选项 1:没有 th:object

    <form th:action="@{/destination}">
          <input type="text" th:value="${service.firstName}" name="service.firstName"/>
          <input type="text" th:value="${fleet.firstName}" name="fleet.firstName"/>
          <button type="submit">Go</button>
    </form>
    

    选项 2:

    网络

    <form th:action="@{/destination}" th:object="${myThymeleafFormObject}">
    
    public class ThymeleafForm {
    
        private String fleetFirstName;
        private String serviceFirstName;
    
        ...
    
    }
    

    服务

    public class MyService {
    
        // To avoid complexity maps the ThymeleafForm in different JPA entities 
        // Logic and repository calls
    }
    

    存储库

    public class FleetServiceRepositoryJPA {    
        //Database operations for fleet table
    }
    
    public class ServiceRepositoryJPA { 
        //Database operations for service table
    }
    

    【讨论】:

    • 我不明白。那是为了什么?
    • 您不能在同一个表单中使用不同对象的字段。因此,您需要将所有字段放在同一个对象中,然后根据您的逻辑拆分表单。第二种选择是有两个分开的表格。
    • 我不能有两个分开的表格。而且我不知道如何将这些字段放在同一个对象中。
    • 为什么我必须分离私有字符串fleetFirstName和私有字符串serviceFirstName。他们成为一体的部分在哪里。我将把什么对象放到 th:field 中?
    • 如果我只将名字放入 DTO 会怎样?然后使用 DTO 对象并将其保存到服务和车队表?你认为这会奏效吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-29
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    相关资源
    最近更新 更多