java - 组装对象时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 的城市对象。结果保持不变,返回一个带有空评论列表的城市对象。
解决方案
推荐阅读
- python - 使用 pytest 和 pytest-mock 使用 json 参数模拟 Flask POST 请求
- reinforcement-learning - 有谁知道为什么我会在使用“import pybulletgym”时出现这个错误
- django - 如何将函数应用于 values_list 查找中的字段
- css - 在物化 CSS 上更改日期选择器颜色
- java - OpenCSV + RestTemplate:数组类型
- python - 获取由熊猫中另一列排序的列划分的第一个匹配项
- asp.net-mvc - ASP.net core 3.1 中控制器和剃须刀页面之间的路由
- mysql - 当多条记录同时插入时,如何避免重复的序号?
- javascript - 全局覆盖默认类型属性
- python - 如果输入不在域中,则使 matplotlib 不绘图