如何在弹簧数据中选择字段?

时间:2017-05-03 14:25:03

标签: java spring-data spring-data-jpa

我有如下实体。

@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;
    }
}

我的控制器是:

@RestController
public class DEmoController {

    @Autowired
    private ProductRepository productRepository;

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

它将加载产品的类型和系列。 我可以只加载类型但不能加载序列吗?
我不想将fetch=FetchType.LAZY添加到串口,因为如果下次我想加载序列但不加载类型,那就太糟糕了。

2 个答案:

答案 0 :(得分:0)

检查Projection interface

创建界面ProductProjection

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

并在您Repository

中添加方法

List<ProductProjection> findAllProjection()

答案 1 :(得分:0)

这是fetch=FetchType.LAZY的重点。在您明确要求之前,它不会加载任何类型/字段。

看看这个问题:Link