Spring Data Repository with several entities

237 views Asked by At

I have 2 entities according to the following code that have a one-to-one relationship.

    @Entity
    public class Student
    {
        
        @Id
        @GeneratedValue
        private long id;
        
        private String name;
        
        @OneToOne( fetch = FetchType.LAZY )
        private Passport passport;
        
    }


    @Entity
    public class Passport
    {

        @Id
        @GeneratedValue
        private long id;

        private String number;

        @OneToOne( fetch = FetchType.LAZY, mappedBy = "passport" )
        private Student student;

}

Do I need create two spring Data Repositories to store Passport and Student ?
Or there is a better solution ?

1

There are 1 answers

0
Andrew Lalis On

Yes. It is generally good practice to define a single Data-Access-Object (repository) for each type of entity in your model.

Often what I'll do to help with the tediousness is define a 'mapped superclass' BaseEntity that has an id and a creation timestamp, and create a repository for that base entity. Then all other entities can extend from that repository, and they all get access to common methods like findById(Long id).