4 Replies Latest reply on Jan 19, 2006 9:51 AM by dornus

    Prevent EntityManager persisting

      I have the following situation...

      @Stateless
      public class MyClassBean implements MyClass {
       @PersistenceContext(unitName = "blah")
       EntityManager em;
      
       public List<MyTable> doSomething(){
       final Query q = em.createQuery(
       "from MyTable "
       );
       List<MyTable> myList = q.getResultList();
      
       // Now I wish to take myList, and change fields
       // in it for display purposes only
       for (MyTable item : myList) {
       item.setName("|--"+item.getName());
       }
      
       return myList;
       }
      }
      


      When I do this, it updates the field in the database ("so the field now starts with "|--"). I only want that first part for display purposes. I need to insert "|--" at this time, instead of later on in the code, so logically I thought I could alter my object temporarily without it being update in the database.

      I am at no time explicitly calling em.persist() or em.merge()

      How do I prevent this?

        • 1. Re: Prevent EntityManager persisting

          In the mean time, I made a transient variable in the MyTable class called displayName.

          Hopefully there is a better solution?

          • 2. Re: Prevent EntityManager persisting
            ejb3workshop

            You are breaking MVC in a bad way. You seem to doing presentation logic inside a session bean. session beans are about business logic. Rather add the additional field on the client side rather then within the session bean itself.

            The reason the database is updated is that you are still working within the entity / persistent context as you are still inside the container. If you had to use a remote client (are you using remote or local interfaces ?) then perform the presentation logic in the client code.

            • 3. Re: Prevent EntityManager persisting
              gavin.king

              I think what he's doing is fine.

              The idea that session beans are never used in the presentation tier is oldstyle EJB2 thinking.

              To stop a method from persisting changes, mark it @TransactionAttribute(NOT_SUPPORTED).

              • 4. Re: Prevent EntityManager persisting

                Excellent, thank you.


                FYI, slight change but it should be

                @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)