首页 > 解决方案 > 组装对象时JPA的工作原理

问题描述

@Entity
public class City {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String name;
    private String country;
    private String description;
    @OneToMany(mappedBy = "city", cascade=CascadeType.REMOVE)
    private Set<Comment> comments = new LinkedHashSet<Comment>();
}
@Entity
public class Comment {
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String description;
    @ManyToOne
    @JoinColumn(name="city_id")
    private City city;
}

public interface CityRepository extends JpaRepository<City, Integer> {}
public interface CommentRepository extends JpaRepository<Comment, Integer> {}

@Service
public class MainService {

    CityRepository cityRepository;
    CommentRepository commentRepository;
    
    @Autowired
    public MainService(CityRepository cityRepository,
            CommentRepository commentRepository) {
        this.cityRepository = cityRepository;
        this.commentRepository = commentRepository;
    }

    public Comment addComment() {
        Comment comment = new Comment("some description");
        City city = new City("Belgrad", "Serbia", "Noice.");
    
        comment.setCity(city);

        cityRepository.save(city);
        commentRepository.save(comment);


        City cityFromDatabase = cityRepository.findById(1).get(); **//call 1**
        return comment;
    }
    public City getCity(int id) {
        return cityRepository.findById(1).get(); **//call 2**
    }
}

当我从控制器拨打电话 1 时,城市对象将有空的评论列表,但是当我拨打电话 2 时,城市对象的评论对象列表中将有 1 条评论。有人可以向我解释为什么会这样吗?
我的猜测是它与记忆有关。当我们第一次调用时,我们已经在内存中有 id 为 1 的城市对象,所以我们的持久性提供者只是返回它。在调用 2 中我们没有任何东西,所以我们的提供者必须组装一个新的,它确实返回一个具有正确状态的对象。但是我再次尝试在调用 1 之前删除参考城市。我将其设置为 null,然后调用 .gc() 并让主线程休眠 10 秒,然后再调用存储库以给我 id 为 1 的城市对象。结果保持不变,返回一个带有空评论列表的城市对象。

标签: javaspringjpamemoryspring-data-jpa

解决方案


推荐阅读