Last active
August 29, 2015 14:04
-
-
Save jesuino/90e8dbea1dee3440f2eb to your computer and use it in GitHub Desktop.
Service and model classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
public class Person { | |
@GeneratedValue | |
@Id | |
private long id; | |
private String firstName; | |
private String lastName; | |
private String rfid; | |
private String job; | |
private int age; | |
@ManyToMany(fetch=FetchType.EAGER) | |
@JoinTable(name = "person_role", joinColumns = @JoinColumn(name = "person_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id")) | |
private List roles; | |
// getters and setters | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Stateless | |
@Default | |
public class PersonService { | |
@PersistenceContext(unitName = "primary") | |
protected EntityManager em; | |
public void save(Person p) { | |
em.persist(p); | |
} | |
public void remove(Person p) { | |
Person toRemove = findById(p.getId()); | |
em.remove(toRemove); | |
} | |
public List<Person> listAll() { | |
CriteriaQuery<Person> cq = em.getCriteriaBuilder().createQuery( | |
Person.class); | |
cq.select(cq.from(Person.class)); | |
return em.createQuery(cq).getResultList(); | |
} | |
public Person findById(long id) { | |
return em.find(Person.class, id); | |
} | |
public Person findByRFID(String rfid) { | |
CriteriaQuery<Person> cq = em.getCriteriaBuilder().createQuery( | |
Person.class); | |
Root<Person> person = cq.from(Person.class); | |
cq.where(person.get("rfid").in(rfid)); | |
Person result; | |
try { | |
result = em.createQuery(cq).getSingleResult(); | |
} catch (NoResultException e) { | |
result = null; | |
} | |
return result; | |
} | |
public Person update(Person p) { | |
return em.merge(p); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment