Я пытаюсь удалить сущность из памяти (на данный момент я не использую БД) с JPA, когда я использую remove
, а затем попытаюсь найти удаленный объект, который он показывает null
, но когда я использую findAll
метод его получение всех данных (с удаленным объектом) ...Не удается удалить объект с JPA
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";
}
почему вы звоните профиля "delProfile = this.entityManager.merge (профиль);" снова в функции удаления? – SerhatCan
Поскольку я читал где-то, что я должен вызвать merge, чтобы получить ту же транзакцию – Kratul
Кстати, хотя deleteById - это правильный способ сделать это, как в примере, который я дал в своем ответе, если вы все еще не хотите менять свой код , проблема в том, что при удалении вы также сохраняете другой объект, вызывая «Профиль delProfile = this.entityManager.merge (profile)»; и удаление вновь созданного объекта одновременно. Таким образом, ваш фактический объект не будет удален. – SerhatCan