It looks like Spring-Data projections don't works properly. Also the @CreationDate annotated fields are nulls. What's wrong with that?
This is Category entity class:
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;
}
}
The projection's interface:
public interface ShowCategoryDto {
@Value("#{target.id}")
Long getId();
String getName();
Set<ProductBasicDto> getProducts();
}
And Repository:
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);
}
Now when I call the findAll
method it returns:
creationDate:null
id:1
lastModifiedDate:null
name:"wwwwwwwwww"
parentCategory:null
products:[]
So I see two problems here. The first one is that projection isn't applied, and the second one is that there are nulls in the creationDate
and lastModifiedDate
fields. Does someone know the reason why this happens and could share it with me?
The findAll
is the method of CrudRepository interface, its signature is:
List<T> findAll()
where T
is your entity .
If you need a custom method that return projections instead of the entities you should use another name for the method, for example:
List<MyProjection> findBy()
List<MyProjection> findAllBy()
List<MyProjection> findProjectionsBy()
List<MyProjection> getProjectionsBy()
etc.
More info:
Query Creation
Working with projections
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.