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