Loading ...
Sorry, an error occurred while loading the content.

JPA em.persist não atualiza o registro, insere nova mente

Expand Messages
  • Jean Jorge Michel
    Pessoal, tenho uma app JSF 2.0 que faz o seguinte quando atualizo um objeto: MenagedBean = facade (EJB) Eu estou tentando atualizar um registro assim: public
    Message 1 of 1 , Apr 9, 2012
    • 0 Attachment
      Pessoal, tenho uma app JSF 2.0 que faz o seguinte quando atualizo um objeto:

      MenagedBean => facade (EJB)

      Eu estou tentando atualizar um registro assim:

        public void saveOrUpdate(Note note) {
            em.persist(note);
        }
       
      Quando eu insiro um objeto funciona perfeitamente, mas quando eu atualizo ele está inserindo novamente.

      Eu li no stackoverflow.com sobre o uso de persist vs. merge, ambos parecem me atender, porque não estou preocupado com fazer em.persist(n) e depois n.setQualquerCoisa() e essa alteração não "commitar".

      Agora, pergunto aos colegas, porque raios o persist não está atualizando o meu objeto (claro que eu não alterei o Id dele nem nada, somente um campo String)?

      Códigos:

      package com.model.entity;

      import java.io.Serializable;
      import java.util.Date;
      import javax.persistence.Entity;
      import javax.persistence.GeneratedValue;
      import javax.persistence.GenerationType;
      import javax.persistence.Id;
      import javax.persistence.JoinColumn;
      import javax.persistence.ManyToOne;
      import javax.persistence.Table;
      import javax.persistence.Temporal;
      import javax.persistence.TemporalType;
      import javax.persistence.Transient;

      @Entity
      @Table(name="Note")
      public class Note implements Serializable {
         
          @Transient
          private static final long serialVersionUID = 5776215245000569399L;
         
          @Id
          @GeneratedValue(strategy=GenerationType.IDENTITY)
          private Integer id;
         
          @ManyToOne
          @JoinColumn(name="USERID", referencedColumnName = "ID", nullable = false)
          private User owner;
          private String text;
         
          @Temporal(TemporalType.TIMESTAMP)
          private Date creationDate;
         
          public void setId(Integer id) {
              this.id = id;
          }
         
          public Integer getId() {
              return id;
          }
         
          public void setOwner(User owner) {
              this.owner = owner;
          }
         
          public User getOwner() {
              return owner;
          }
         
          public void setText(String text) {
              this.text = text;
          }
         
          public String getText() {
              return text;
          }
         
          public void setCreationDate(Date creationDate) {
              this.creationDate = creationDate;
          }
         
          public Date getCreationDate() {
              return creationDate;
          }
         
          public Note() {
              super();
          }
         
          public Note(Integer id, User owner, String text, Date creationDate) {
              super();
              this.id = id;
              this.owner = owner;
              this.text = text;
              this.creationDate = creationDate;
          }
         
          @Override
          public String toString() {
              return "Note [id=" + id + ", owner=" + owner + ", text=" + text
                      + ", creationDate=" + creationDate + "]";
          }

          @Override
          public int hashCode() {
              final int prime = 31;
              int result = 1;
              result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode());
              result = prime * result + ((owner == null) ? 0 : owner.hashCode());
              result = prime * result + ((text == null) ? 0 : text.hashCode());
              return result;
          }

          @Override
          public boolean equals(Object obj) {
              if (this == obj)
                  return true;
              if (obj == null)
                  return false;
              if (getClass() != obj.getClass())
                  return false;
              Note other = (Note) obj;
              if (creationDate == null) {
                  if (other.creationDate != null)
                      return false;
              }
              else if (!creationDate.equals(other.creationDate))
                  return false;
              if (owner == null) {
                  if (other.owner != null)
                      return false;
              }
              else if (!owner.equals(other.owner))
                  return false;
              if (text == null) {
                  if (other.text != null)
                      return false;
              }
              else if (!text.equals(other.text))
                  return false;
              return true;
          }
      }


      package com.model.entity.facade;

      //import static com.util.MessagesUtil.getMessage;
      import java.util.Date;
      import java.util.Iterator;
      import java.util.List;
      import java.util.logging.Logger;
      import javax.ejb.Stateless;
      import javax.persistence.EntityManager;
      import javax.persistence.PersistenceContext;
      import javax.persistence.TemporalType;
      import com.model.entity.Note;
      import com.model.entity.User;

      @Stateless
      @SuppressWarnings("unchecked")
      public class NoteFacadeImplementation implements NoteFacade {
         
          @PersistenceContext
          EntityManager em;
          private Logger logger = Logger.getLogger("com.model.entity.facade.NoteFacadeImplementation");
         
          /* (non-Javadoc)
           * @see com.model.entity.facade.NoteFacade#saveOrUpdate(com.model.entity.Note)
           */
          @Override
          public void saveOrUpdate(Note note) {
              em.persist(note);
          }
         
          /* (non-Javadoc)
           * @see com.model.entity.facade.NoteFacade#listAll()
           */
          @Override
          public List<Note> listAll() {
              List<Note> notes = em.createQuery("SELECT n FROM Note n").getResultList();
              return notes;
          }
         
          /* (non-Javadoc)
           * @see com.model.entity.facade.NoteFacade#findUserByOwner(com.model.entity.User)
           */
          @Override
          public List<Note> findNoteByOwner(User owner) {
              List<Note> notes = em.createQuery("SELECT n FROM Note n WHERE n.owner = :owner")
                  .setParameter("owner", owner)
                  .getResultList();
             
              return notes;
          }
         
          /* (non-Javadoc)
           * @see com.model.entity.facade.NoteFacade#findUserByCreationDate(com.model.entity.User, java.util.Date)
           */
          @Override
          public List<Note> findNoteByCreationDate(User owner, Date creationDate) {
              List<Note> notes = em.createQuery("SELECT n FROM Note n WHERE n.owner = :owner AND n.creationDate = :creationDate")
                  .setParameter("owner", owner)
                  .setParameter("creationDate", creationDate, TemporalType.TIMESTAMP)
                  .getResultList();
             
              return notes;
          }
         
          /* (non-Javadoc)
           * @see com.model.entity.facade.NoteFacade#findNoteByOwnerAndLikeText(com.model.entity.User, java.lang.String)
           */
          @Override
          public List<Note> findNoteByOwnerAndLikeText(User owner, String text) {
              List<Note> notes = em.createQuery("SELECT n FROM Note n WHERE n.owner = :owner AND UPPER(n.text) LIKE UPPER(:text)")
                  .setParameter("owner", owner)
                  .setParameter("text", "%" + text + "%")
                  .getResultList();
             
              return notes;
          }
         
          /* (non-Javadoc)
           * @see com.model.entity.facade.NoteFacade#findNoteByOwnerAndText(com.model.entity.User, java.lang.String)
           */
          @Override
          public List<Note> findNoteByOwnerAndText(User owner, String text) {
              List<Note> notes = em.createQuery("SELECT n FROM Note n WHERE n.owner = :owner AND UPPER(n.text) = UPPER(:text)")
                  .setParameter("owner", owner)
                  .setParameter("text", text)
                  .getResultList();
             
              return notes;
          }
         
          /* (non-Javadoc)
           * @see com.model.entity.facade.NoteFacade#findNoteByExample(com.model.entity.Note)
           */
          @Override
          public Note findNoteByExample(Note note) {
              List<Note> notes = em.createQuery("SELECT n FROM Note n WHERE n.id = :id")
                  .setParameter("id", note.getId())
                  .getResultList();
             
              Note n = null;
             
              if(! notes.isEmpty()) {
                  Iterator<Note> iterator = notes.iterator();
                 
                  while(iterator.hasNext()) {
                      n = iterator.next();
                     
                      if(n.equals(note)) {
                          return n;
                      }
                  }
              }
             
              return n;
          }
         
          /* (non-Javadoc)
           * @see com.model.entity.facade.NoteFacade#delete(com.model.entity.Note)
           */
          @Override
          public void delete(Note note) {
              logger.info("Deleting the note " + note);
              Note n = findNoteByExample(note);
              em.remove(n);
          }
      }


      package com.managedbean;

      import java.io.Serializable;
      import java.util.GregorianCalendar;
      import java.util.logging.Logger;
      import javax.annotation.PostConstruct;
      import javax.ejb.EJB;
      import javax.faces.application.FacesMessage;
      import javax.faces.bean.ManagedBean;
      import javax.faces.context.FacesContext;
      import com.model.entity.Note;
      import com.model.entity.User;
      import com.model.entity.facade.NoteFacade;
      import static com.util.MessagesUtil.getMessage;

      @ManagedBean(name="registerlNoteBean")
      public class RegisterNoteBean  implements Serializable {
         
          private static final long serialVersionUID = -1680405953390469322L;
         
          private String text;
          private boolean registerAction;
          private Logger logger = Logger.getLogger("com.managedbean.RegisterNoteBean");
          @EJB
          private NoteFacade noteFacade;
          private final FacesContext facesContext = FacesContext.getCurrentInstance();
         
          public void setText(String text) {
              this.text = text;
          }
         
          public String getText() {
              return text;
          }
         
          public void setRegisterAction(boolean registerAction) {
              this.registerAction = registerAction;
          }
         
          public boolean isRegisterAction() {
              return this.registerAction;
          }
         
          public RegisterNoteBean() {
              super();
              logger.info("Creating registerlNoteBean");
          }
         
          @PostConstruct
          public void validateIsAnUpdate () {
              logger.info("Testing if is an update or a register action");
             
              Note n = (Note)this.facesContext.getExternalContext().getSessionMap().get("noteToUpdate");
             
              if (n != null) {
                  this.text = n.getText();
                  this.registerAction = false;
              }
              else {
                  this.registerAction = true;
              }
          }
         
          public String doSaveOrUpdate() {
              logger.info("Saving or updating a note");
             
              if (registerAction) {
                  logger.info("Saving");
                  User u = (User)this.facesContext.getExternalContext().getSessionMap().get("userAuthenticated");
                  Note note = null;
                  note = new Note(0, u, this.text, new GregorianCalendar().getTime());
                  noteFacade.saveOrUpdate(note);
                  this.facesContext.addMessage(null, new FacesMessage(getMessage("noteCreated"), null));
              }
              else {
                  logger.info("Updating");
                  Note n = (Note)this.facesContext.getExternalContext().getSessionMap().get("noteToUpdate");
                  logger.info("Updating the note: " + n.getId());
                  this.facesContext.getExternalContext().getSessionMap().remove(n);
                  n.setText(this.text);
                  noteFacade.saveOrUpdate(n);
                  this.facesContext.getExternalContext().getSessionMap().put("noteToUpdate", n);
                  this.facesContext.addMessage(null, new FacesMessage(getMessage("noteUpdated"), null));
              }
             
              return "/faces/register_note.xhtml";
          }
      }


      Obrigado pela ajuda.




      --
      Best regards,
      Jean J. Michel

      * Sent from my cellphone, please forgive the lack of accents and punctuation marks ;)
      My blogs: http://www.jeanjmichel.blogspot.com and http://www.anonymousbiker.wordpress.com
      My Twitter: http://twitter.com/jeanjmichel
    Your message has been successfully submitted and would be delivered to recipients shortly.