Question

I'm looking for how to I can do an update at an item of my entity using jpacontainer. The item is unique and I want to update by this item.

@Entity
@Table(name="curriculum")
public class Curriculum implements Serializable{
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue
    private Long idCurriculum;

    @Size(min=5, max=50)
    @NotNull
    @NotEmpty   
    private String nome;

    @Email
    @NotEmpty
    @NotNull
    @Size(max=250)
    @Column(unique=true)
    private String email;

    @NotEmpty
    @NotNull
    @Size(min=8, max=8)
    private String senha;
}

In this case I want to update senha(password) using email that is an unique key

Any idea ?

/** Edited */

I managed to do using Criteria. I don't know if that is correct but for now it's works.

here, how I did.

public void changePassword(String email, String password){
     try{
            EntityManager em = datasource.getEntityProvider().getEntityManager();       
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery<Curriculum> c = cb.createQuery(Curriculum.class);
            Root<Curriculum> curriculum = c.from(Curriculum.class);
            c.where(
                    cb.equal(curriculum.get("email"), email)
                    );
            TypedQuery q = em.createQuery(c);
            Curriculum ce = (Curriculum)q.getSingleResult(); //ce = curriculum entity
            datasource.getItem(ce.getIdCurriculum()).getItemProperty("password").setValue(password);

        }catch(Exception e){
            Notification.show("Curriculum not found \n", 
                      e.getLocalizedMessage(), 
                      Type.ERROR_MESSAGE);
        }
     }

There's another solution more simple using only JPAContainer ?

Was it helpful?

Solution

As email is not the Id field, I would use a Query (typed, named or native) first to get the Curriculum object to be updated, then I would update it by EntityManager.merge:

EntityManager em = ...
TypedQuery<Curriculum> query = em.createQuery(
           "SELECT c FROM Curriculum c " +
           "WHERE c.email = :p1",
           Curriculum.class);
query.setParameter("p1", "myemail@myhost.com");
Curriculum curriculum = (Curriculum) query.getSingleResult();
curriculum.setSenha("mypwd");
em.merge(curriculum);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top