2

I've got two different scenarios where I have to retrieve data from one or two entities that have a relation between them.

@Entity
@Table
public class Level2 {
    @Id
    @Column(name = "id_level_2")
    private Integer idLevel2;

    @Column(name = "id_level_1")
    private Integer idLevel1;

    @ManyToOne
    @JoinColumn(name = "id_level_1", referencedColumnName = "id_level_1", insertable =  false, updatable = false)
    private Level1 level1;

Case A) Just want to retrieve de level2 without Level1 information, just the two ids. Case B) All the Level2 with the Level1 information.

This works but I am wondering if it is a good practice.

Thanks

Rachel
  • 65
  • 11
  • 1
    You actually can get the id from `level1` already, e.g. `level1.getId()` should not trigger lazy-loading if everything is configured properly (e.g. `level1` should be lazy loaded which many-to-one should do by default - but please check). If you want to load `level1` eagerly either use a fetch query or an entity graph. – Thomas Nov 04 '21 at 16:37
  • 1
    Btw, if `level1` wasn't lazy then your case A) could only be done by a query like `select idLevel2, idLevel1 ...` but that could also be done by `select idLevel2, level1.id ...`. Case B) would either require a fetch query or an entity graph anyway unless `level1` always is eagerly fetched (in which case we're back to a query for case A). – Thomas Nov 04 '21 at 16:40
  • @Thomas, so in this scenario is ok to have the Column and the JoinColumn annotation using the same column name? – Rachel Nov 04 '21 at 17:19
  • 1
    It can be ok but it also can introduce problems and since it's not necessary I'd get rid of it. A simple design results in easier to understand and maintain code. – Thomas Nov 04 '21 at 17:29

0 Answers0