Advertisement
Guest User

Untitled

a guest
Mar 20th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. @Service(CustomerService.NAME)
  2. public class CustomerServiceBean implements CustomerService {
  3.  
  4.  
  5. @Inject
  6. private Persistence persistence;
  7.  
  8. @Inject
  9. private Metadata metadata;
  10.  
  11.  
  12. @Override
  13. public void createOrUpdateCustomer(String name, String email) {
  14. try (Transaction tx = persistence.createTransaction()) {
  15. // Search for existing customers with the given name
  16. TypedQuery<Customer> query = persistence.getEntityManager().createQuery(
  17. "select c from sales$Customer c where c.name = :name", Customer.class);
  18. query.setParameter("name", name);
  19. List<Customer> customers = query.getResultList();
  20. if (customers.size() == 0) {
  21. // no customer with the given name, creating it
  22. Customer customer = metadata.create(Customer.class);
  23. customer.setName(name);
  24. customer.setEmail(email);
  25. // persist the new instance
  26. persistence.getEntityManager().persist(customer);
  27. } else if (customers.size() == 1) {
  28. // a customer found, updating it
  29. Customer customer = customers.get(0);
  30. customer.setEmail(email);
  31. // the loaded customer is in Managed state and will be saved to the database on transaction commit
  32. } else {
  33. // more than one customer found, raising an error
  34. throw new IllegalStateException("More than one customer with name " + name);
  35. }
  36. tx.commit();
  37. }
  38. }
  39.  
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement