Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Service(CustomerService.NAME)
- public class CustomerServiceBean implements CustomerService {
- @Inject
- private Persistence persistence;
- @Inject
- private Metadata metadata;
- @Override
- public void createOrUpdateCustomer(String name, String email) {
- try (Transaction tx = persistence.createTransaction()) {
- // Search for existing customers with the given name
- TypedQuery<Customer> query = persistence.getEntityManager().createQuery(
- "select c from sales$Customer c where c.name = :name", Customer.class);
- query.setParameter("name", name);
- List<Customer> customers = query.getResultList();
- if (customers.size() == 0) {
- // no customer with the given name, creating it
- Customer customer = metadata.create(Customer.class);
- customer.setName(name);
- customer.setEmail(email);
- // persist the new instance
- persistence.getEntityManager().persist(customer);
- } else if (customers.size() == 1) {
- // a customer found, updating it
- Customer customer = customers.get(0);
- customer.setEmail(email);
- // the loaded customer is in Managed state and will be saved to the database on transaction commit
- } else {
- // more than one customer found, raising an error
- throw new IllegalStateException("More than one customer with name " + name);
- }
- tx.commit();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement