在JPA中,无法通过OneToMany关联获取数据

时间:2019-05-20 06:56:53

标签: spring-boot spring-data-jpa one-to-many

我正在使用JPA进行春季启动。我的一个实体类与其关联表具有一对多关联。如果关联表中没有单个对象,则在尝试加载所有详细信息时,我将无法获取任何关联数据。

主要实体

@Entity
@Table(name = "tbl_search_request")
public class SearchRequest implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @OneToMany(fetch = FetchType.EAGER, orphanRemoval = false)
    @JoinColumn(name = "search_request_id")
    private List<PersonSearchAssociation> personSearchAssociations = new ArrayList<>();


    public SearchRequest() {
        super();
        // TODO Auto-generated constructor stub
    }


}

关联实体

@Entity
@Table(name = "tbl_person_search_association")
public class PersonSearchAssociation implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;


    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "search_request_id", nullable = false)
    private SearchRequest searchRequest;

}

//存储库接口

@Repository("searchRequestRepository")
public interface SearchRequestRepository extends JpaRepository<SearchRequest, Integer> {
}

//服务等级

@Service("SearchService")
 @Scope("prototype")
 public class SearchServiceImpl implements SearchService {
       @Autowired
       private SearchRequestRepository searchRequestRepository;

         private loadData(){

            java.util.List<SearchRequest> searchRequestList=searchRequestRepository.findAll();

            }

      }

2 个答案:

答案 0 :(得分:-1)

在映射定义中添加级联类型,然后它应该可以工作。

答案 1 :(得分:-2)

在您的SearchRequest实体中尝试@OneToMany(cascade = CascadeType.ALL, mappedBy = "searchRequest", fetch = FetchType.EAGER)