Reputation: 634
Hi Have two entity employee details and address with one to many relation ship.
Employee Entity
@Entity
@Table(name = "employeeInfo")
public class EmployeeInfo {
int employeeId;
String employeeName;
@OneToMany
@JoinColumn(name = "employeeId")
private List<Address> employeeAddress;
}
Address Entity
@Entity
@Table(name = "address")
public class Address{
int employeeId;
String address;
String landMark;
String addressType
}
in the above structure, the employee has multiple addresses like
Home address, work address, permanent address current address
whenever I am trying to get entity by spring data
public EmployeeInfo findByEmployeeId(int employeeId)
it is returning me the result with four address. is there any way to get the address on the bases of condition
For example
select * from employeeInfo where address ="homeAddress" and employeeId =1;
Upvotes: 0
Views: 445
Reputation: 6936
You basically want to retrieve an address of a known employee, so you could query for an address:
select a from address a where a.adressType= :type and a.employeeId = :id
or you could take advantage of the 'Spring Data repository query derivation mechanism'
and add this method in you AddressRepository
:
Address findByAddressTypeAndEmployeeId(String type, Integer id)
EDIT
if you need other fields/data you could use a DTO.
public class EmployeeAddressInfo{
String employeeName;
Address address;
EmployeeAddressInfo(String employeeName, Address address){
this.employeeName = employeeName;
this.address = address;
}
//getters setters
}
and create this DTO in you EmployeeRepository
@Query(select new com.example.EmployeeAddressInfo(employeeName, address) from employeeInfo where address.addressType =:type and employeeId =:id)
EmployeeAddressInfo findAddressInfo(String type, Long id);
or you could use other types of projections
Upvotes: 1