Home > database >  Retrieving data using JPARepository
Retrieving data using JPARepository

Time:08-22

I'm learning Java web dev using Spring Boot and I have real trouble understanding how to retrieve data using JPARepository.

Let have an entity Workspace:

@Entity
@Table(name = "workspace")
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true) // solves problem with inheritance from BaseModel
public class Workspace extends BaseModel{

    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    private Account createdBy;

    @ManyToMany(mappedBy = "workspaces")
    private List<Account> members = new ArrayList<>();

    @OneToMany(mappedBy = "workspace", orphanRemoval = true, cascade = CascadeType.ALL)
    private List<TimeEntry> timeEntries = new ArrayList<>();

}

Now I have a repository:

public interface WorkspaceRepository extends JpaRepository<Workspace, Long> {

    Workspace findById(long id);

}

and a service:

@Service
@RequiredArgsConstructor
public class WorkspaceService {

    private final WorkspaceRepository repository;

    @Transactional(readOnly = true)
    public Workspace getWorkspace(long id) {
        return this.repository.findById(id);
    }
}

My question is. Is it really necessary to add method Workspace findById(long id) into my repository, since this method is already in JPARepository?

If I do not add the method to my WorkspaceRepository then I can just change the service like this:

    @Transactional(readOnly = true)
    public Optional<Workspace> getWorkspace(long id) {
        return this.repository.findById(id);
    }

or like this:

    @Transactional(readOnly = true)
    public Workspace getWorkspace(long id) {
        return this.repository.findById(id).get();
    }

What is the other benefit of adding a method into my repository instead of that Spring will generate implementation with the desired type (Workspace)?

CodePudding user response:

You dont have to add findById to your repository. If you add you gain nothing. Whenever you need some specific queryies like "select * from workspace where name = "blabla" ". You can use jpaquery to implement this like that Workspace findWorkspaceByName(String name). And hibernate will create select query for you in backside. Some basic queries are predefined in JPARepository and CRUDRepository that is why we use theese instead of EntityManager

  • Related