简体   繁体   中英

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

If I want to show in a view (using thymeleaf) all columns of the table, do I have to hard code it calling each attribute in the view like this?

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

Or is there a way to iterate over the properties of the entity in the Thymeleaf view to avoid having to call all 40 attributes by name?

So far I've just found a way of iterating over List of Entities, but not the attributes of one Entity.

I haven't come across such feature in Thymeleaf, but if I absolutely had to do this (creating a column for each property of an entity), I would do something like this in my @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";
}

and create such @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
        }
    }
}

And then in the template.html :

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

But note that if you add a property to MyEntity.class , it might break your table, so it would probably be better to somehow hard-code your fields, eg like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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