Want to improve as a dev?

I send a short email every workday about Spring topics, API development and improving as a dev.

I understand and agree to the privacy policy

Let's Build an API Together - Part 22

26.01.2018 by Jens in API Series | APIs | Newsletter

In this episode, we are adjusting the model.

The Board is also a simple JPA Entity with an auto-generated id and name and a user reference. The user reference is right now a simple free-form text field. More on this when we build the user stuff next week.

@Entity
@Data
@NoArgsConstructor
public class Board {

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

    @Column(length=100)
    private String name;

    @Column(length=100)
    private String user;

    @OneToMany(mappedBy="board", fetch=FetchType.LAZY)
    private List<Task> tasks = new ArrayList<Task>();
}

The only interesting part is that we declare a reference to the tasks. It is using a bi-directional @OneToMany; meaning a single board instance can have multiple tasks.

The other side of the bi-directonal mapping looks like:

@Entity
@Data
@NoArgsConstructor
public class Task {

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

    @Column(length = 2048)
    private String content;

    @Column(length = 10)
    private String category;

    @Column(length = 10)
    @Enumerated(EnumType.STRING)
    private Lane lane;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "board_id")
    private Board board;

}

Both are set to Lazy fetching, so JPA will only load the actual value when we access them.

This bi-directional mapping is the best compromise between OOD and JPA performance. You can learn more here. If JPA performance is more important, we could switch to the pure @ManyToOne on the task and retrieve them by a query.

It depends, like anything, on a particular use case. Read the article and be aware of the consequences.


comments powered by Disqus