@Override @Transactional public void deleteArticle(Long personId, Article news) { User u = entityManager.find(User.class, personId); for (Role r : u.getRole()) { if (Objects.equals(r.getName(), "ADMIN")) { entityManager.remove(entityManager.contains(news) ? news : entityManager.merge(news)); } } }
private boolean isAdmin(Long pId) { Query q = entityManager.createQuery("SELECT p FROM User p WHERE p.id=:pId"); q.setParameter("pId", pId); User p = (User) q.getSingleResult(); for (Role r : p.getRole()) { if (Objects.equals(r.getName(), "ADMIN")) { return true; } } return false; }
@Override @Transactional public Article saveArticle(Long personId, Article newNews) { Article newsOne = new Article(); if (newNews.getId() != null) newsOne = newNews; else { newsOne.setContext(newNews.getContext()); newsOne.setContent(newNews.getContent()); } User p = entityManager.find(User.class, personId); newsOne.setCreator(p); boolean isAdmin = false; boolean isModer = false; for (Role r : newsOne.getCreator().getRole()) { if (Objects.equals(r.getName(), "ADMIN")) isAdmin = true; else if (Objects.equals(r.getName(), "MODERATOR")) isModer = true; } if (isAdmin && newsOne.getId() == null) entityManager.persist(newsOne); else if (isAdmin) entityManager.merge(newsOne); else if (isModer && newsOne.getId() != null) entityManager.merge(newsOne); return newsOne; }