0
votes

I have two entity which has no primary key or foreign key reference, but i need to have uni directional entity for using the or extracting relational entity. Using Spring Data jpa.

below are entity classes :

@Entity
@Table(name="CAR_PARTS")
Class  CarParts {

@id
@Column(name="PART_ID")
private Long id;
@Column(name="PART_NAME")
private String partName

}

@Entity
@Table(name="CAR_HISTORY")
Class  CarHistory {

@id
@Column(name="CAR_HIST_ID")
private Long id;

@Column(name="PART_NAME")
private String part;

@ManyToOne(fetch=FetchType.lazy,optional=false)
    @JoinColumn(name="PART_NAME",referencedColumnName="PART_NAME",insertable=false,updatable=false)
    private CarPart carpart;
@column(name="SUBMIT_DATE")
private Date submitedDate;

    }

DAO Class:

public interface CarHistoryDAO extends JpaRepository,JpaSpecificationExecutor { }

Service Class :

  public class CarhistoryServiceImpl {

  @Autowired
  private CarHistoryDAo carHistoryDAO;

  public List<CarHistory> findCarHistory(Date startDate, Date endDate) {
    List<CarHistory> hists = 
     carhistoryDAO.findAll(where(historyBySubmitedDate(startDate,endDate)));
   }
   public static Specification<CarHistory> historyBySubmitedDate(
            final Date startDate, final Date endDate) {
        return new Specification<CarHistory>() {
            @Override
            public Predicate toPredicate(Root<CarHistory> variableRoot,
                    CriteriaQuery<?> q, CriteriaBuilder cb) {

                Predicate p1 = cb.between(
                        variableRoot.<Date> get("submitedDate"),
                        DateUtils.truncate(startDate, Calendar.DAY_OF_MONTH),
                        DateUtils.ceiling(endDate, Calendar.DAY_OF_MONTH));

                return cb.and(p1);
            }
    };
}

with the above relation , when ever fetch CarHistory entity i am getting n+1 iteration for Carpart entity,

I am using Spring data jpa, implemented to use specification in spring data jpa. Is there any way i can avoid n+1 iteration issue. I tried with onetoone instead of manytoone

1
which repository method are you using for retrieval? or is it custom. Add that please - Maciej Kowalski
updated the dao and service - Rajar R

1 Answers

0
votes

To avoid n+1 issue you have to fetch CarPart instances along with the CarHistory entities. There are multiple solutions:

  1. Map CarHistory.carPart as EAGER (not a good solution)

  2. Write custom query and fetch CarHistory.carPart eagerly, e.g. from CarHistory ch JOIN FETCH ch.carPart where ...

Here is the article explaining how to initialize lazy associations and when to use them