Rohail Butt
Rohail Butt

Reputation: 461

Spring data jpa search filter by foreign key and type

Model Class Vehicle

@Column(name="type",nullable=false)
private String type;

@Column(name="last_service_date",nullable=false)
private String lastServiceDate;

@Column(name="seats",nullable=false)
private Long seats;

@Column(name="bags_capacity",nullable=false)
private Long bagsCapacity;

@Column(name="milage",nullable=false)
private Long milage;

//for Franchise object id
private transient Long fId;

@ManyToOne
 @JoinColumn(name="franchise_id")
 private Franchise fkFranchiseId;



@Repository
public interface VehicleRepository extends JpaRepository<Vehicle,Long> 
{


 }

I am using spring data jpa repositories and want to search Vehicle by type and foreignKey=>(zipcode) how can i find

enter image description here

Upvotes: 3

Views: 10592

Answers (4)

Seyed Ali Roshan
Seyed Ali Roshan

Reputation: 1574

for those who have a more complex object and want to keep their code, u can also use @Query for fetching data. u just need to do this like this:

@Repository
public interface VehicleRepo extends JpaRepository<Vehicle, String> {
  @Query("from Vehicle v where v.type = :type and v.fkFranchise.zipCode = :zipCode")
  List<Vehicle> findAllByTypeAndZipCode(String type, String zipCode);
 }

Upvotes: 0

Vikram Singh Shekhawat
Vikram Singh Shekhawat

Reputation: 762

You can use JPA repo method name query documented here https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.query-creation

public interface VehicleRepo extends JpaRepository<Vehicle, String> {

  List<Vehicle> findAllByTypeAndFkFranchiseIdZipCode((String type, String zipCode);

  Page<Vehicle> findAllByTypeAndFkFranchiseIdZipCode((String type, String zipCode,Pageable page);

 }

Upvotes: 1

Jaganath Kamble
Jaganath Kamble

Reputation: 556

 List<Vehicle> findAllByTypeAndFkFranchiseId_ZipCode(String type, String zipCode);

Upvotes: 1

Vladlen Gladis
Vladlen Gladis

Reputation: 1787

Just add a method in your Vehicle JPA repository interface as follow:

findAllByTypeAndFkFranchiseIdZipCode(String type, String zipCode);

And also you are welcome to check docs of Spring Data Jpa

Upvotes: 13

Related Questions