0

How to get DEPARTMENT_ID of the base class without loading sub-class in Spring boot JPA

For example we have a base model:

@Entity
@Table(name = "TM_POSITIONS")
public class PositionEntity {

    @Id
    @SequenceGenerator(name = "PositionsSequence", sequenceName = "TM_POSITIONS_SEQ", allocationSize = 1, initialValue = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PositionsSequence")
    private long id;

    @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.REFRESH)
    @JoinColumn(name = "DEPARTMENT_ID")
    private DepartmentModel department;
...

So, how to just get DEPARTMENT_ID without bundle it and load another object. In some cases, I need to get related Model and in some cases, I need to get just DEPARTMENT_ID.

Ruslan Skaldin
  • 981
  • 16
  • 29

2 Answers2

3

You can create a responseDTO class and a mapper class for that.

@ApiModel
public class positionEntityResponseDTO{

private long id;
private long departmentId;

//getter & setter

}

And the mapper class look like

 @Service
    public class ResponseMapper{
     public positionEntityResponseDTO map (PositionEntity entity){
       positionEntityResponseDTO response = new positionEntityResponseDTO();
        response.setId(entity.getId);
        response.setDepartmentId(entity.getDepartment.getId();
        return response;

    }

    }

now suppose somewhere you write

@Autowired
private ResponseMapper mapper;
positionEntityResponseDTO response= mapper.map(repository.save(entity));

now you can pass only DEPARTMENT_ID by response object. hope this works for you.

Aritra Paul
  • 834
  • 1
  • 8
  • 14
1

First of all you need to set the fetch = FetchType.LAZY. In the EAGER way the sub-class will always be loaded.

If you set the fetch type lazy, you can reach the sub-class's id (primary-key) field without extra db queries.

So if you write position.getDepartment().getId() you will get the id and it won't cost anything.

Keep in mind, that other method calls on the sub-class will be load it from the database, e.g.: toString, equals, or getName() /if there is such a method/.

In the case you need the sub-class for some other functionalities, you should write another query in your reposiroty which will fetch the sub-class too.

@Query("SELECT pos FROM Position LEFT JOIN FETCH pos.department")

With JOIN FETCH Spring Data JPA will generate a single query which will join the two table, so you can avoid the N+1 problem.

Szilárd Fodor
  • 354
  • 2
  • 9