0

I have entity as follow.

@Entity
@Table(name = "BankProduct")
public class Product {
    @Id
    @GeneratedValue(strategy =  GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToOne
    private ProductUseType type;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @ManyToOne
    private ProductSerial serial;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public ProductUseType getType() {
        return type;
    }

    public void setType(ProductUseType type) {
        this.type = type;
    }

        public ProductSerial getSerial() {
        return serial;
    }

    public void setSerial(ProductSerial serial) {
        this.serial = serial;
    }
}

My controller is :

@RestController
public class DEmoController {

    @Autowired
    private ProductRepository productRepository;

    @GetMapping("/products")
    public Returns products() {
        return new Returns(ReturnStatus.SUCCESS.getStatus(), productRepository.findAll(), null);
    }
}

It will load both of type and serial of product. Can I only load type but not to load serial?
I don't want to add fetch=FetchType.LAZY to serial, because if next time I want to load serial but not to load type, it will be terrible.

nameless
  • 2,015
  • 2
  • 11
  • 10

2 Answers2

0

Check the Projection interface

Create a interface ProductProjection

interface ProductProjection {
    String getName();
    String getType();
}

and add a method in you Repository

List<ProductProjection> findAllProjection()

Sigrist
  • 1,471
  • 2
  • 14
  • 18
  • It means I want to define many interfaces for each query? Is there a easier way ? – nameless May 03 '17 at 14:47
  • Unfortunately, as far as know, yes. An alternative is to use GraphQL instead. But in your request you should "ask" which fields you want. Take a look here: http://graphql.org/ – Sigrist May 03 '17 at 16:23
0

That's the whole point of fetch=FetchType.LAZY. It'll not load any of your types/fields until you ask for them explicitly.

Take a look at this question: Link

Community
  • 1
  • 1
RoyalBigMack
  • 620
  • 7
  • 7
  • But if it want to load those lazy list data, how to load them all without foreach to load those lazy data? – nameless May 03 '17 at 14:44
  • You don't really need to 'for each' every field in your class (if that's what you mean). Lazy loading means that the field will not load from the DB until it is explicitly called. – RoyalBigMack May 04 '17 at 10:16