wolandec wolandec - 1 month ago 11
Java Question

Spring JPA repository method does'nt set values of entity after query

Page entity.

@Entity
@Table(name = "pages", schema = "admin")
public class Page implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true)
private Integer id;

@Column(name = "name")
private String name;


@ManyToOne(targetEntity = Partition.class, fetch = FetchType.LAZY)
private Partition partition;

@Column(name = "is_startable")
private Boolean isStartable;

@Column(name = "priority")
private Integer priority;

@Column(name = "prefix_granted_authority")
private String prefixGrantedAuthority;

@OneToMany(mappedBy = "page", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
private List<Permission> permissions;

@Column(name = "link", unique = true)
private String link;


PageRepository

List<Page> findByPermissionsGroupsOrderByPartitionNameAscNameAsc(@Param(value = "group") Group group);


PageServiceImpl

@Override
public Collection<Page> getAccessedPages(Group group) {
try {
List<Page> pages = pageRepository.findByPermissionsGroupsOrderByPartitionNameAscNameAsc(group);
return pages;
} catch (Exception ex) {
logger.error("getPage error", ex);
return null;
}
}


getAccessedPages return real List of page entities(not null), but all fields in entities are null.

Why?

Answer

I also encounter this problem while ago, it looks like spring data does some kind lazy instantiation.
So if you not access this fields inside of your transaction, they will stay null. Add annotation @Transactional on method where are you calling this request and problem will be solved.