Home > Enterprise >  Spring JPA Two Entities for same DB table
Spring JPA Two Entities for same DB table

Time:10-16

I am writing Spring Boot Data JPA application and I have following situation:

I have 2 database queries fetching from same table but they are fetching different columns and data based on their WHERE clauses. For example:

SELECT CAR_TYPE, CAR_MODEL, CAR_YEAR, ACCIDENT_YEAR, BUY_DAY FROM CAR WHERE ACCIDENT_YEAR IS NULL

, and

SELECT CAR_MODEL, CAR_YEAR FROM CAR WHERE CAR_YEAR >= CURRENT_YEAR

As you can see these 2 queries (whose results will be exposed through 2 different API points) reference the same table CAR, but return different fields and have different WHERE clauses.

I know in JPA, I have to create an entity CarEntity like:

@Entity
@Table(name = "CAR")
public class CarEntity {
   // I can only have fields from one or the other query 
   // here, so I guess I have to have 2 of these
}

, but my problem is that this entity needs to apply for the 2 different queries (with different fields returned, different data, different WHERE clauses).

So, it looks like I have to have actually 2 CarEntity classes. But, I am not sure how to make these 2 CarEntities so they both reference the same table CAR?

CodePudding user response:

You can do by using projection that basically you define an interface with field methods which you want to get them. Projections

@Entity
public class Car implement CarSummary { // if you want you can implement JIC
  
  private UUID id;
  private String carType;
  private String carModel;
  private LocalDateTime carYear;
  
  //getters and setters

}


public interface CarSummary {

  String getCardModel();
  String getCarYear();

}

Then on your query.

public interface CarRepository extends Repository<Car, UUID> {
  Collection<CarSummary> findByCarYearGreaterThan(LocalDateTime now);
  Collection<Car> findByAccidentYearIsNull();
} 
  • Related