简体   繁体   中英

How to handle multiple fields in JPA Repository query methods?

I have Person - a JPA entity which has several @OneToOne mappings to some other entities like Address, House and Car. I want to find the person who is having a specific house and a specific car in one query.

For example, if we want to find a Person by id, we can use the findById method. If we want to find using name, I can define a findByName method in my repository.

My question is : What will the method signature be if I want to select a person with more than 2 fields set?

I have tried selecting using House by a method findByHouse() which is only using one property. I want to select using multiple properties.

Person class :

@Entity(name="Person")
@Table(name="person")
@Data
class Person{

@Column(name="HouseID")
Integer houseID;

@Column(name="CarID")
Integer carID;

@Column(name="AddressID")
Integer addressID;

@OneToOne ( fetch= FetchType.EAGER, cascade = CascadeType.ALL )
@JoinColumn ( name = "houseID" )
private House house;

@OneToOne ( fetch= FetchType.EAGER, cascade = CascadeType.ALL )
@JoinColumn ( name = "carID" )
private Car car;

@OneToOne ( fetch= FetchType.EAGER, cascade = CascadeType.ALL )
@JoinColumn ( name = "addressID" )
private Address address;

}

Now the Repository:

public interface PersonRepository extends JpaRepository<Person,Long>{

   @Query("select p from Person p where p.house.id=:id")
   Person findByHouse(@Param("id")Integer houseID);
}

I expect a Person record where the house, car and address is set to a specific value that is passed in the query.

simply pass multiple parameters and extend your query with and for multiple requirements.

public interface PersonRepository extends JpaRepository<Person,Long>{

   @Query("select p from Person p where p.house.id=:houseId and p.carID =:carId")
   Person findByHouseAndCar(@Param("houseId")Integer houseID, @Param("carId")Integer carID);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM