Jéjé Jéjé - 1 month ago 7
Java Question

What's kind of object use to do a form with a select field?

In my model, I have this two classes

Sport
and
SportSession
:

@Entity
@Table(name = "sport")
public class Sport implements Serializable {

@Id
@Column(name="sport_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@Column(name = "name", nullable = false, unique = true)
private String name;
}


@Entity
@Table(name = "sport_session")
public class SportSession implements Serializable {

@Id
@Column(name="sport_session_id")
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

// ...

@ManyToOne
@JoinColumn(name = "sport_id", nullable = false)
private Sport sport;
}
}


With Thymeleaf, I want to do a form allowing to create a
SportSession
.

I want this form contains a
<select>
field with the name of all the sports in order to associate a
Sport
to a
SportSession
.

My question is : How kind of object should be send from my controller to the view?

Should I create a new object
SportSessionForm
that contains the list of all the sports, and also a
Sport
member to store the sport selected by the user?

Is SportSession is sufficient to do that? And what about DTO object ?
In short, what is the best practice in this case?

Thanks already.

Answer

It is better to maintain two separate Beans one for the presentation layer (SportSessionFormBean) and Business/Entiry Bean (SportSession) for the Business tier (services layer).

You need to convert the presentation bean data (SportSessionFormBean) to the Business bean in the Controller classes and then pass that to Business Bean Object (SportSession)to the Services layer. Service layer uses this Business Bean to interact with DAO classes which persist or do some transactions with the database.

How kind of object should be send from my controller to the view ? Should I create a new object SportSessionForm that contains the list of all the sports, and also a Sport member to store the sport selected by the user?

Yes, SportSessionFormBean interacts with the HTML front end.

Is SportSession is sufficient to do that? And what about DTO object ? In short, what is the best practice in this case?

As explained above, do not mix up the presentation tier data with business tier (Services layer) data. Services are reusable components and they interact with multiple end points (like a controller or a different web service etc..).