Get entity property with Spring JPA

I'm using Spring JPA in my DAO layer. I have an entity Projet having inside an entity property Client:

Project.java

@Entity

public class Project {

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

private int projetId;

private String libelle;

@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)

@JoinColumn(name="client_id")

private Client client;

// ... constructors, getters & setters

}

Client.java

@Entity

public class Client {

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

private int clientId;

private String denomination;

// ... constructors, getters & setters

}

in my DAO interface I have the following specifications:

ProjetDao.java

@Repository

@Transactional

public interface ProjetDao extends CrudRepository<Projet, Integer> {

@Transactional

public Projet findByLibelle(String libelle);

@Transactional

public Projet findByProjetId(int projetId);

}

My question is: How can I specify in my DAO interface a method that will return all clients distinct in List<Client>?

网友答案:

From the documentation and JIRA:

List<Project> findAllDistinctBy();

The query builder mechanism built into Spring Data repository infrastructure is useful for building constraining queries over entities of the repository. The mechanism strips the prefixes find…By, read…By, query…By, count…By, and get…By from the method and starts parsing the rest of it. The introducing clause can contain further expressions such as a Distinct to set a distinct flag on the query to be created. However, the first By acts as delimiter to indicate the start of the actual criteria. At a very basic level you can define conditions on entity properties and concatenate them with And and Or.

网友答案:

You are dealing with a one-to-one relationship, in this case I guess the list that you need is not really related to specific project, you just want a distinct list of clients.
You will need to create another repository (ClientRepository) for the Client entity and add a findAllDistinct method in this repository.