Thymeleaf-如何将具有复合键的对象列表绑定到选择对象

时间:2019-05-18 09:37:01

标签: spring-boot thymeleaf

我正在为这种情况而苦苦挣扎。

我有一个Threshold对象,该对象与具有复合键的ToolCommand对象具有ManyToMany关系。

public class Threshold{
...
@ManyToMany
private Set<ToolCommand> toolCommands

...
}

public class ToolCommand implements Serializable{

@EmbeddedId
private ToolCommandKey id;

@ManyToMany(mappedBy="toolCommands")
private Set<Threshold> thresholds;
 ...
}

@Embeddable
public class ToolCommandKey implements Serializable{

    @Column(name="tool_id")
    private long toolId;

    @Column(name="command_id")
    private long commandId;

}

现在,问题出在百里香,我需要公开多个选择,您可以在其中选择用于阈值的工具命令,因为我不知道要在绑定中放置th:value属性中的内容

如果我用这种方式行不通

<select class="form-control" th:field="*{toolCommands}" th:multiple="multiple">
                        <option th:each="t : ${toolCommands}" th:value="${t.id}" th:text="${t.tool.name + '-' + t.command.name}">Option</option>
                    </select>

因为它将t.id解析为toString()

所以我以这种方式尝试了

<select class="form-control" th:field="*{toolCommands}" th:multiple="multiple">
                        <option th:each="t : ${toolCommands}" th:value="${t.id.toolId + ',' + t.id.commandId}"
                            th:text="${t.tool.name + '-' + t.command.name}">Option</option>
                    </select>

并添加了格式化程序

@Component
public class ToolCommandFormatter implements Formatter<ToolCommand>{

    private final Logger logger = LoggerFactory.getLogger(ToolCommandFormatter.class);

    @Autowired
    private IToolService toolService;

    @Autowired
    private ICommandService commandService;

    @Autowired
    private IToolCommandService toolCommandService;

    @Override
    public String print(ToolCommand object, Locale locale) {

        return object.getTool().getToolId() + "," + object.getCommand().getCommandId() ;
    }

    @Override
    public ToolCommand parse(String text, Locale locale) throws ParseException {
        logger.debug(text);
        String[] ids = text.split(",");
        Tool t = toolService.findByToolId(Long.parseLong(ids[0]));
        Command c = commandService.finfById(Long.parseLong(ids[1]));
        return toolCommandService.findById(t, c);
//      return null;
    }

现在,当我保存新的阈值时它可以工作,但是当尝试编辑现有阈值时,它无法呈现所选内容。

有没有解决这种情况的标准方法?

0 个答案:

没有答案