Matelutex
Matelutex

Reputation: 2220

Spring OneToMany - how to limit list of objects to list of one field from that object

I wonder if it's possible to fetch List of some specific field of objects instead of list of whole objects from relation @OneToMany:

@Entity
public class Template
...
private Driver driver;
prvate boolean isIpen;

@OneToMany(

            mappedBy = "template"
    )
    private List<Warehouse> warehouses = new ArrayList<>();

I want to fetch list of Template objects with list of Warehouse.name (List<String>) instead of List<Warehouse>. Is it possible?

My repository:

@QueryHints(value = {
            @QueryHint(name = org.hibernate.jpa.QueryHints.HINT_PASS_DISTINCT_THROUGH, value = "false")
    })
    @Query("SELECT at FROM Template at " +
            "WHERE at.driver.id = :companyId " +
            "AND at.isOpen = true")
    @EntityGraph(attributePaths = {"warehouses"})
    List<Template> findAllOpenByCompanyId(Long companyId, Pageable pageable);

I wanto to reduce the number of queries to database

Upvotes: 0

Views: 561

Answers (1)

Ben
Ben

Reputation: 86

I would try using an @ElementCollection with @CollectionTable instead of the @OneToMany.

So it would turn like this:

@Entity
public class Template
...
private Driver driver;
prvate boolean isIpen;

@ElementCollection
@CollectionTable(
    name="the name of the warehouse table",
    joinColumns=@JoinColumn(name="warehouse id column")
)
@Column(name="warehouse name column in warehouse table")
private List<String> warehouseNames = new ArrayList<>();

I'm unable to test this at the moment, but hopefully it helps.

Upvotes: 1

Related Questions