[英]Can't remove entity with JPA
我試圖從內存中刪除一個實體(目前我不使用DB),當我使用remove
然后嘗試找到它顯示為null
的已刪除實體時,但是當我使用findAll
方法時它會檢索所有數據(已刪除實體)...
Profile.java
@Entity
@Table(name = "profile")
public class Profile {
@Id
@GeneratedValue
private Long id;
private String nombre;
private Boolean restrictedAccess;
private Boolean canValidate;
// private Set<AccessField> accessFields = new HashSet<AccessField>();
// private Set<AccessEntity> accessEntities = new HashSet<AccessEntity>();
@OneToMany(mappedBy = "profile", fetch = FetchType.EAGER)
private Set<AccessMenu> menuSections = new HashSet<AccessMenu>();
@OneToMany(mappedBy = "profile", fetch = FetchType.EAGER)
private Set<User> users = new HashSet<User>();
[getters and setters]
ProfileRepository
@Repository
@Transactional
public class ProfileRepository {
@PersistenceContext
private EntityManager entityManager;
public Profile save(Profile p) {
p = this.entityManager.merge(p);
this.entityManager.flush();
return p;
}
public void delete(Long id){
Profile profile = this.entityManager.find(Profile.class, id);
this.entityManager.remove(profile);
}
public List<Profile> findAll() {
CriteriaQuery cq = this.entityManager.getCriteriaBuilder().createQuery();
cq.select(cq.from(Profile.class));
return (List<Profile>) this.entityManager.createQuery(cq).getResultList();
}
public Profile findById(Long id){
return this.entityManager.find(Profile.class, id);
}
}
控制器方法
@RequestMapping(value="profile/delete/{idProfile}", method = RequestMethod.GET)
public String delete(@PathVariable String idProfile,RedirectAttributes ra, Model model){
profileRepo.delete(Long.valueOf(idProfile));
model.addAttribute("profiles", profileRepo.findAll());
return "profile/list";
}
如果您正在嘗試使用控制器中的Id刪除實體,請執行profileRepo.deleteById(Long.valueOf(idProfile));
這個,不像這個profileRepo.delete(profileRepo.findById(Long.valueOf(idProfile)));
還可以使用這些存儲庫函數,
public void deleteArtistById(Long artistId) {
Artist artist = manager.find(Artist.class, artistId);
if (artist != null) {
manager.getTransaction().begin();
manager.remove(artist);
manager.getTransaction().commit();
}
}
public void deleteArtist(Artist artist) {
manager.getTransaction().begin();
manager.remove(artist);
manager.getTransaction().commit();
}
您可以查看此鏈接以獲取更多詳細信息: http : //kodejava.org/how-do-i-delete-entity-object-in-jpa/
最后我找到了一個解決方案,問題是當我試圖刪除Profile
, users
和menuSections
都有相關數據,所以最后我把menuSections
的cascade = CascadeType.REMOVE
和users
設置的profile
屬性設置為null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.