JPA2. 0: delete entity in onetomany relationship
•
Java
How to delete an entity in a onetomany relationship
@Entity @NamedQueries({ @NamedQuery(name="User.findByUserNamePassword",query="select c from User c where c.userName = :userName AND c.password = :password") }) @Table(name="\"USER\"") public class User implements Serializable { @OneToMany(mappedBy="user",cascade=CascadeType.ALL,orphanRemove=true) private List<Profession> professions; public List<Profession> getProfessions() { return professions; } public void setProfessions(List<Profession> professions) { this.professions = professions; } public void addProfession(Profession profession){ if(this.professions == null){ this.professions = new ArrayList<Profession>(); } this.professions.add(profession); profession.setUser(this); } public void removeProfession(Profession profession){ if(this.professions != null){ professions.remove(profession); profession.setUser(null); } } }
Internal professional entity
@Entity public class Profession implements Serializable { @ManyToOne @JoinColumn(name="UserId",nullable=false) private User user; public User getUser() { return user; } public void setUser(User user) { this.user = user; }
Then I have this in my EJB
@Stateless @LocalBean @TransactionAttribute(TransactionAttributeType.required) public class ScholarEJB{ /** * Add a profession to a target user * @param user * @param profession */ public void addProfession(User user,Profession profession){ //Put the user in a managed state. It is important to do this before //adding a new profession onto user user = find(User.class,user.getId()); user.addProfession(profession); this.create(user); //This is persist action } public void removeProfession(User user,user.getId()); user.remove(user); this.update(user); //merge action //this.create(user) //also try this as well,but it does not work } }
Now addprofessional works beautifully, but removeprofessional doesn't work Do not know why? Please help. Do I need to evict the cache?
Solution
If a profession is only part of this relationship, you can ensure that when a profession is deleted from the user's collection, it will also be deleted from the database by opening orphanremoval on the onetomany side of the relationship
@OneToMany(mappedBy="user",orphanRemoval=true) private List<Profession> professions;
This is what the JPA 2.0 specification says
The JPA 2.0 specification points this out
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码