繁体   English   中英

遍历视图中的实体属性,Spring 使用 thymeleaf 引导 JPA

[英]Iterate over Entity attributes in view, Spring Boot JPA with thymeleaf

I'm using Spring Boot JPA with Thymeleaf, I'm dealing with a Class (Entity) linked to a table with around 40 columns, so my entity model class has around 40 attributes (each one linked to each column of the table).

如果我想在视图中显示(使用 thymeleaf)表的所有列,我是否必须像这样对视图中的每个属性进行硬编码?

<td th:text=${entity.attribute1> </td>} <td th:text=${entity.attribute2> </td>} <td th:text=${entity.attribute3> </td>} <td th:text=${entity.attributeN...> </td>}

或者有没有办法在 Thymeleaf 视图中迭代实体的属性以避免必须按名称调用所有 40 个属性?

到目前为止,我刚刚找到了一种迭代实体列表的方法,但不是一个实体的属性。

我在 Thymeleaf 中没有遇到过这样的功能,但是如果我绝对必须这样做(为实体的每个属性创建一个列),我会在我的 @Controller 中做这样的事情:

@GetMapping( "/mypage" )
public String myPage(Model model) {
    List<MyEntity> myEntities = dao.getList(MyEntity.class);
    List<String> fieldNames = MyEntity.class.getDeclaredFields().stream()
            .map(field -> field.getName()).collect(Collectors.toList());

    model.addAttribute("myEntities", myEntities);
    model.addAttribute("fieldNames", fieldNames);
    return "template";
}

并创建这样的@Service:

@Service
public class FieldService {
    public Object getFieldValue( Object root, String fieldName ) {
        try {
            Field field = root.getClass().getDeclaredField( fieldName );
            Method getter = root.getClass().getDeclaredMethod( 
                (field.getType().equals( boolean.class ) ? "is" : "get") 
                    + field.getName().substring(0, 1).toUpperCase( Locale.ROOT)
                    + field.getName().substring(1)
            );

            return getter.invoke(root);
        } catch (Exception e) {
            // log exception
        }
    }
}

然后在template.html中:

<tr th:each="myEntity : ${myEntities}">
    <td th:each="fieldName : ${fieldNames}" 
        th:text="${@fieldService.getFieldValue(myEntity, fieldName)}"></td>
</tr>

但请注意,如果您向MyEntity.class添加一个属性,它可能会破坏您的表格,因此以某种方式对您的字段进行硬编码可能会更好,例如:

List<String> fieldNames = new ArrayList<>(Arrays.asList("attribute1", "attribute2", ...));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM