我正在尝试使用 JPA 从内存中删除一个实体(目前我不使用 DB),当我使用 remove
然后尝试找到它显示的已删除实体时 null
,但是当我使用 findAll
方法时,它会检索所有数据(已删除实体)...
配置文件.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]
资料库
@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);
}
}
Controller 方法
@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";
}
最佳答案
如果您正尝试通过在 Controller 中使用 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/
关于java - 无法使用 JPA 删除实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32005468/