Selecting a Linked Entity View
Explore how to implement entity selection and linking in Thymeleaf and Spring Boot applications. Understand creating Team entities, managing many-to-one relationships with User as coach, and building forms using DTOs. Learn to handle selection inputs in HTML and ensure functionality with integration tests using Cypress.
We'll cover the following...
Implementation
A common requirement in an application is the ability to select an entity from a list of entities to link that entity to another entity. Let’s make it practical.
We’ll create a Team entity. Each Team has a coach. When we create a form to create or edit a Team, we will have a combobox to select a coach. That combobox will contain all users of the application.
Creating a team will look like this:
We’ll start by creating our Team entity using JPearl:
mvn jpearl:generate -Dentity=Team
By expanding on that generated code, we have our Team entity like this:
On lines 17 and 18, we’ll create a link between Team and User by using the many-to-one relationship. This allows for a single coach to coach different teams.
@ManyToOne(fetch = FetchType.LAZY)
private User coach;
To support this Team entity, we need to create a database table:
We will also create a TeamService:
The TeamServiceImpl will use the TeamRepository for the database interaction:
The TeamRepository is a normal CrudRepository, but it ...