简体   繁体   English

@ManyToMany并更新实体

[英]@ManyToMany and updating entity

I have User class, which has some additional attributes: 我有User类,它有一些额外的属性:

@Entity
@Table(name="\"user\"")
public class User implements UserDetails {
    private String username;
    private String password;
    @ManyToMany(fetch = FetchType.EAGER)
    private Collection<House> houses;
}

Now, if I invoke some method that changes one of the houses (for example changes its name property), I still get the old value of the house if I call: 现在,如果我调用一些更改其中一个房屋的方法(例如更改其名称属性),如果我打电话,我仍然会得到房子的旧值:

User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
user.getHouses(); <- value of name property in house is not updated

How can I make sure that it is always updated? 我怎样才能确保它始终更新?

I would suggest you to change @ManyToMany(fetch = FetchType.EAGER) to @ManyToMany(fetch = FetchType.LAZY) . 我建议你将@ManyToMany(fetch = FetchType.EAGER)更改为@ManyToMany(fetch = FetchType.LAZY) Because EAGER fetch immediately the object the first time you call it and with LAZY you have the id and you will fetch by demand, that means, with lazy you will get from the database the last state of your object. 因为EAGER在第一次调用它时立即获取对象,并且使用LAZY你有id,你将按需求获取,这意味着,懒惰你将从数据库中获取对象的最后状态。

You are missing a few details, based on your given information: 根据您提供的信息,您缺少一些细节:

The Cascade is missing, there are all kind of cascade types, for the simplicity let's assume that you want every change made on your User entity will result affect on the related entity which is House, so you'll have to add Cascade.all 缺少Cascade,有各种级联类型,为简单起见,我们假设您希望对您的User实体所做的每一个更改都会影响相关实体House,因此您必须添加Cascade.all

What about your @JoinTable and @JoinCoumn ? 你的@JoinTable@JoinCoumn怎么@JoinCoumn it also doesn't define in your entities relationship. 它也没有在您的实体关系中定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM