dynamic adding of persons

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

dynamic adding of persons

bigal.nz
I want some feedback on my approach for this project which is using hibernate and thymeleaf.

I have a Episode entity which has a one to many with people entity.

I have a html form which is used to both display existing episodes and create new episodes (is it good practise to have the same form do both?)

Episode always has at least two people so the first two input groups look like

<input th:field="${persons[0].person.surname"}>
<input th:field="${persons[1].person.surname"}>

And further down the form I have a hidden person set of fields, and the "add person" button removed the hidden tag

These fields are initalised at

<input th:field="${persons[2].person.surname}">


If I use a set entity to map the collection between episode and person this code will generate a index out of bounds error when I try to load the form to create a new episode (because a new episode has no persons attached).

However if I use a list, and I try to create a new episode the form will load and the server passes in a new  episode with 3 "empty people" attached (so no out of bounds errors).

My add button will now work and I have some code to update the indexes for each new person that is added

List below - works

@Entity
public class Episode {

        public Episode() {
        }

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        // other stuff
        @OneToMany(mappedBy = "episode", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
        private List<EpisodePerson> persons = new ArrayList<EpisodePerson>();

@Entity
public class Episode {

        public Episode() {
        }

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;

        @OneToMany(mappedBy = "episode", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
        private Set<EpisodePerson> persons = new HashSet<>();

Doesnt work - out of bounds exception when loading the new form.

My whole approach could be wrong and I am open to suggestions on better ways to do this?

Maybe since person1 and person2 are on the first page I could have a th:if=(some test is itsStat>2) then th:each and another one for th:if=${itsstat=1} th:each etc?

Thanks

Al
Reply | Threaded
Open this post in threaded view
|

Re: dynamic adding of persons

Alexela
Hi,

2 Osservation
the first:
I'am not sure you can use the type Set in
private Set<EpisodePerson> persons = new HashSet<>();

try to use
private List<EpisodePerson> persons = new ArrayList<>();

the second:
you have to use the preprocessing of thymleaf like follows

<div each="pers,persStat :persons">
           <input th:field="*{persons[__${persStat .index}__].surname}"/>
</div>

Hope to be useful