Example usage for javax.persistence EntityManager find

List of usage examples for javax.persistence EntityManager find

Introduction

In this page you can find the example usage for javax.persistence EntityManager find.

Prototype

public <T> T find(Class<T> entityClass, Object primaryKey);

Source Link

Document

Find by primary key.

Usage

From source file:facades.PersonFacadeDB.java

@Override
public Person delete(Integer id) throws NotFoundException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceFileName);
    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();//from   ww  w  . j av  a2 s .co m

    Person p = em.find(Person.class, id);

    if (p == null) {
        transaction.rollback();
        throw new NotFoundException("No person for the given id");
    } else {
        em.remove(p);
        transaction.commit();
    }

    return p;
}

From source file:org.hibernate.search.demo.SearchDemo.java

private void updateTitle(long id, String title) {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();//from  w ww.  j  a  v  a2 s.  co  m
    try {
        Product product = em.find(Product.class, id);
        if (product != null) {
            product.setTitle(title);
        }
    } finally {
        em.getTransaction().commit();
        em.close();
    }
}

From source file:edu.csueb.cs6320.utils.UserService.java

public boolean updatePassword(long userid, String newPassword) {
    EntityManager em = Persistence.createEntityManagerFactory("TestPU").createEntityManager();
    User u = em.find(User.class, userid);
    if (u == null) {
        return false;
    }//  w  ww.j  a  v a 2s  .co m

    em.getTransaction().begin();

    // TODO: This block of code really belongs in User.setPassword()
    String salt = Auth.getSalt();
    u.setSalt(salt);
    try {
        u.setSaltedHashedPassword(Auth.hashPassword(newPassword, salt));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        em.getTransaction().rollback();
        return false;
    }
    em.getTransaction().commit();
    em.close();

    return true;
}

From source file:com.emc.plants.service.impl.LoginBean.java

/**
 * Update an existing user.//from ww w  . j  a va  2 s  . c o m
 *
 * @param customerID The customer ID.
 * @param firstName First name.
 * @param lastName Last name.
 * @param addr1 Address line 1.
 * @param addr2 Address line 2.
 * @param addrCity City address information.
 * @param addrState State address information.
 * @param addrZip Zip code address information.
 * @param phone User's phone number.
 * @return CustomerInfo
 */
public CustomerInfo updateUser(String customerID, String firstName, String lastName, String addr1, String addr2,
        String addrCity, String addrState, String addrZip, String phone) {
    CustomerInfo customerInfo = null;
    // TODO: lowp: no lock check is performed to see if cust data has changed since fetch!
    /*
     customerHome = (CustomerHome) Util.getEJBLocalHome("java:comp/env/ejb/Customer",
     com.ibm.websphere.samples.pbwjpa.CustomerHome.class);
             
     Customer customer = customerHome.findByPrimaryKeyUpdate(customerID);
     customer.update(firstName, lastName, addr1, addr2, addrCity, addrState, addrZip, phone);
     customerInfo = new CustomerInfo(customer);
     */
    EntityManager em = entityManagerFactory.createEntityManager();
    em.getTransaction().begin();
    Customer c = em.find(Customer.class, customerID);
    em.lock(c, LockModeType.WRITE);
    em.refresh(c);
    // TODO: lowp: test and set for update performance?
    c.setFirstName(firstName);
    c.setLastName(lastName);
    c.setAddr1(addr1);
    c.setAddr2(addr2);
    c.setAddrCity(addrCity);
    c.setAddrState(addrState);
    c.setAddrZip(addrZip);
    c.setPhone(phone);

    customerInfo = new CustomerInfo(c);
    em.getTransaction().commit();
    return customerInfo;
}

From source file:org.apache.juddi.v3.auth.jboss.JBossAuthenticator.java

public UddiEntityPublisher identify(String authInfo, String authorizedName) throws AuthenticationException {
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    Publisher publisher = null;/*from  w  w  w .ja  v a  2  s  .  co  m*/
    try {
        tx.begin();
        publisher = em.find(Publisher.class, authorizedName);
        if (publisher == null)
            throw new UnknownUserException(new ErrorMessage("errors.auth.NoPublisher", authorizedName));

        AuthToken at = em.find(AuthToken.class, authInfo);
        if (at == null)
            throw new AuthTokenRequiredException(new ErrorMessage("E_authTokenRequired", authInfo));
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
    return publisher;
}

From source file:com.emc.plants.service.impl.LoginBean.java

/**
 * Retrieve an existing user./*  ww w .  j a  va 2 s  .  c  o m*/
 * 
 * @param customerID The customer ID.
 * @return CustomerInfo
 */
public CustomerInfo getCustomerInfo(String customerID) {

    //EntityManager em = entityManagerFactory.createEntityManager();

    CustomerInfo customerInfo = null;
    /*
     customerHome = (CustomerHome) Util.getEJBLocalHome("java:comp/env/ejb/Customer",
     com.ibm.websphere.samples.pbwjpa.CustomerHome.class);
             
     Customer customer = customerHome.findByPrimaryKey(new CustomerKey(customerID));
     customerInfo = new CustomerInfo(customer);
     */
    EntityManager em = entityManagerFactory.createEntityManager();
    System.out.println(" Entity Manager :: " + em);
    Customer c = em.find(Customer.class, customerID);
    customerInfo = new CustomerInfo(c);
    return customerInfo;

}

From source file:com.headissue.pigeon.service.AdminSurveyServiceTest.java

EntityManager mergeSurvey(SurveyValue _value) throws Exception {
    EntityManager _manager = factory.createEntityManager();
    try {//  w w w.ja v a 2  s.  c o m
        _manager.getTransaction().begin();
        Survey s = _manager.find(Survey.class, survey.getId());
        adminSurveyService.mergeSurvey(s, _value, UPDATE_DATE, _manager);
        _manager.persist(s);
        _manager.getTransaction().commit();
        survey = s;
    } catch (Exception e) {
        if (_manager.getTransaction().isActive()) {
            _manager.getTransaction().rollback();
        }
        throw e;
    }
    return _manager;
}

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

@SuppressWarnings("unchecked")
public T get(Serializable id) throws ServiceException {
    try {// w w  w  . j  ava 2  s.c o m
        EntityManager entityManager = currentEntityManager();
        T object = entityManager.find(getObjectClass(), id);
        if (object == null) {
            throw new ServiceException("Object Not Found (id=" + id + ')');
        }
        return object;
    } catch (EntityNotFoundException e) {
        logger.error(e.getCause(), e);
        throw new ServiceException("Object Not Found (id=" + id + ')', e);
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        throw new ServiceException("Can't retreive object", e);
    } finally {
        closeEntityManager();
    }
}

From source file:com.headissue.pigeon.admin.AdminSurveyHandler.java

public int overwriteSurvey(SurveyParameter p) {
    checkNotNull(p, "parameter is null");
    checkNotNull(p.getSurvey(), "survey values are null");
    EntityManager _manager = factory.createEntityManager();
    try {/*from ww  w .  ja  v a2  s  .c  om*/
        _manager.getTransaction().begin();
        Survey _survey = _manager.find(Survey.class, p.getSurveyId());
        adminSurveyService.mergeSurvey(_survey, p.getSurvey(), new Date(p.getTimestamp()), _manager);
        _manager.getTransaction().commit();
        return _survey.getId();
    } catch (Exception e) {
        LogUtils.warn(log, e, "save the survey failed");
        if (_manager.getTransaction().isActive()) {
            _manager.getTransaction().rollback();
        }
        return 0;
    } finally {
        _manager.close();
    }
}

From source file:it.infn.ct.futuregateway.apiserver.v1.TaskCollectionService.java

/**
 * Register a new task./*from w  w w .  j  a  v  a  2s. c o  m*/
 *
 * @param task The task to register
 * @return The task registered
 */
@POST
@Status(Response.Status.CREATED)
@Consumes({ MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE })
@Produces(Constants.INDIGOMIMETYPE)
public final Task createTask(final Task task) {
    if (task.getApplicationId() == null) {
        throw new BadRequestException("A valid application for the task" + " must be provided");
    }
    task.addObserver(new TaskObserver(getEntityManagerFactory(), getSubmissionThreadPool()));
    task.setDateCreated(new Date());
    task.setUserName(getUser());
    task.setStatus(Task.STATUS.WAITING);
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        Application app = em.find(Application.class, task.getApplicationId());
        if (app == null) {
            throw new BadRequestException("Application id not valid");
        }
        task.setApplicationDetail(app);
        em.persist(task);
        et.commit();
        log.debug("New task registered: " + task.getId());
    } catch (BadRequestException bre) {
        throw bre;
    } catch (RuntimeException re) {
        log.error("Impossible to create a task");
        log.debug(re);
        throw re;
    } finally {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        em.close();
    }
    return task;
}