当前位置: 首页 > 知识库问答 >
问题:

spring/jpa@onetomany关系返回一个大小为0的列表,而它应该返回更多。为什么?

邹宣
2023-03-14

我在一个项目中使用Spring/JPA,我有一个实体在列表上有@onetomany注释,另一个实体有@manytoone注释。尽管当我通过父实体的id检索父实体时,返回的列表(子实体)的大小始终为0

测试的文本版本

@Test
public void createReccomendation() throws ServiceException, FileNotFoundException, UserDoesNotExistException, UserNameIsNotUniqueException, IllegalUserNameException {
    String uid = UUID.randomUUID().toString();

    Employee employee = employeeService.createEmployee("hi", uid+"@me.com", uid, "secret password", 23.234, 23.23, "image", "23dAD", "seattle", "usa");

    List<String> images = new ArrayList<>();

    String image1 = "image1/url";
    String image2 = "image2/url";
    String image3 = "image3/url";

    images.add(image1);
    images.add(image2);
    images.add(image3);

    Employee e = employeeService.getEmployeeById(employee.getId());
    Recommendation rec = recommendationService.createRecommendation(e.getId(),  "title", "Description", 23.23, 23.23, "persikogatan", "stockholm", "Sweden", images);

    Recommendation rec2 = recommendationService.getRecommendationById(rec.getId());

    Assert.assertEquals(rec.getTitle(), "title");
    Assert.assertEquals(rec.getRecommendationimages().get(0).getPath(), image1);
    Assert.assertEquals(3, rec2.getRecommendationimages().size());
}

此父实体

    @Entity
    @Table(name = "recommendation")
    public class Recommendation extends BusinessEntity {

        @ManyToOne
        @JoinColumn(name = "employeeid")
        private Employee employee;

        @OneToMany(mappedBy = "recommendation", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
        List<RecommendationImage> recommendationimages;

        public Recommendation() {}

        public Recommendation(Employee employee, String title, String description, double targetLat, double targetLong,
                              String street, String city, String country,  List<RecommendationImage> images
                              ) {
            this.employee = employee;
            this.title = title;
            this.description = description;
            this.targetLat = targetLat;
            this.targetLong = targetLong;
            this.street = street;
            this.city = city;
            this.country = country;
            this.active = true;
            this.recommendationimages = images;
        }
@Entity
@Table(name = "recommendationimage")
public class RecommendationImage extends ImageEntity{

    @ManyToOne
    private Recommendation recommendation;
@MappedSuperclass
public abstract class ImageEntity extends BaseEntity{

    @Column(name="path", length=700)
    String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

}
 @Service
    public class RecommendationService{

        private static final Logger log = LogManager.getLogger(DealService.class);


        @Autowired
        RecommendationRepository recommendationRepository;

    public Recommendation getRecommendationById(Long id){
            return recommendationRepository.findOne(id);
        }


    }

public List<RecommendationImage> translateToRecommendationImages(List<String> rawImages) throws ServiceException {
    try{
        List<RecommendationImage> recommendationImages = new ArrayList<>();
        for(String image: rawImages){
            RecommendationImage newImage = new RecommendationImage(image);
            recommendationImages.add(newImage);
        }
        return recommendationImages;
    }catch(Exception e){
        log.warn("** SERVICE EXCEPTION ** FOR METHOD: translateRecommendationImages()");
        throw new ServiceException("Could not translate raw images to RecommendationImage", e);
    }
}

    public Recommendation createRecommendation(Long employeeId, String title, String description, double targetLat,
                                               double targetLong, String street, String city, String country,
                                               List<String> rawImages) throws ServiceException {

        log.info("createRecommendation(): employeeId: "+employeeId+" recommendationTitle: "+title);
        Employee employee=null;
        Recommendation rec=null;
        String imagepath=null;
        try {
            List<RecommendationImage> images = translateToRecommendationImages(rawImages);
            employee = employeeRepository.getEmployeeByid(employeeId);
            rec = new Recommendation(employee, title, description, targetLat, targetLong, street, city, country, images);
//            Recommendation rec2 = CheckProximity.getRecommendationProximity(rec, employee);
            return recommendationRepository.save(rec);
        }catch(Exception e){
            log.warn("** SERVICE EXCEPTION ** FOR METHOD: createRecommendation(): employeeId: "+employeeId);
            e.printStackTrace();
            throw new ServiceException("Could not create recommendation at this time: "+rec.toString(), e);
        }
    }

如有任何帮助,不胜感激,谢谢!

共有1个答案

艾国安
2023-03-14

在提供给您的代码中,没有任何地方实际填充reventionimage的列表。所以我要猜猜。

在处理双向关系时,为了使它们持久化,需要更新关系中没有mappedBy的那一边。我猜您在建议中添加了reventionimage,而没有设置reventionimage建议

通常,您需要这样的方法:

public class Recommendation {
    //...
    private List<RecommendationImage> images = new ArrayList<>();

    public void addRecommendationImage(final RecommendationImage newImage) {
         recommendationImages.add(newImage);
         newImage.setRecommendation(this);
    }
}
public List<RecommendationImage> translateToRecommendationImages(Recommendation recommendation, List<String> rawImages) throws ServiceException {
    //try and whatnot
    for(String image: rawImages){
        recommendation.addRecommendationImage(new RecommendationImage(image));
    }
 类似资料: