Spring Data Projection不起作用

时间:2018-06-01 16:27:03

标签: java spring spring-data-jpa

看起来Spring-Data投影不能正常工作。 @CreationDate带注释的字段也是空值。那有什么不对?

这是类别实体类:

package api.product.domain;

import lombok.AccessLevel;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.hibernate.annotations.DynamicUpdate;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Set;

    @Entity
    @Getter
    @DynamicUpdate
    @EqualsAndHashCode(of = "name")
    @NoArgsConstructor
    class Category {

        @Id
        @GeneratedValue(generator = "ID_GENERATOR")
        private Long id;

        @OneToMany(fetch = FetchType.LAZY, mappedBy = "category", cascade = CascadeType.ALL)
        private Set<Product> products;

        @Setter
        @Accessors(chain = true)
        @Column(unique = true, length = 20, nullable = false)
        private String name;

        @ManyToOne(cascade = {CascadeType.ALL})
        @JoinColumn(name = "parent_category_id")
        @Setter
        @Accessors(chain = true)
        private Category parentCategory;

        @CreatedDate
        @Setter
        private LocalDateTime creationDate;

        @LastModifiedDate
        @Setter
        private LocalDateTime lastModifiedDate;

        Category(String name, Category parentCategory){
            this.name = name;
            this.parentCategory = parentCategory;
        }
    }

投影界面:

public interface ShowCategoryDto {
    @Value("#{target.id}")
    Long getId();
    String getName();
    Set<ProductBasicDto> getProducts();
}

和存储库:

interface CategoryRepository extends Repository<Category, Long> {

    Set<ShowCategoryDto> findAll();

    Optional<ShowCategoryDto> findOptionalById(Long id);

    Category save(Category category);

    Optional<Category> getOneById(Long id);

    void removeById(Long id);
}

现在,当我调用findAll方法时,它会返回:

creationDate:null
id:1
lastModifiedDate:null
name:"wwwwwwwwww"
parentCategory:null
products:[]

所以我在这看到两个问题。第一个是未应用投影,第二个是creationDatelastModifiedDate字段中存在空值。有人知道发生这种情况的原因并可以与我分享吗?

1 个答案:

答案 0 :(得分:2)

findAll是CrudRepository接口的方法,其signature是:

List<T> findAll()

T是您的实体

如果您需要一个返回投影而不是实体的自定义方法,则应使用该方法的其他名称,例如:

List<MyProjection> findBy()
List<MyProjection> findAllBy()
List<MyProjection> findProjectionsBy()
List<MyProjection> getProjectionsBy()

更多信息:
Query Creation
Working with projections