<p>What would be the easiest way to detach a specific JPA Entity Bean that was acquired through an EntityManager. Alternatively, could I have a query return detached objects in the first place so they would essentially act as 'read only'?</p>

<p>The reason why I want to do this is becuase I want to modify the data within the bean - with in my application only, but not ever have it persisted to the database. In my program, I eventually have to call flush() on the EntityManager, which would persist all changes from attached entities to the underyling database, but I want to exclude specific objects.</p>

[{'answer_id': 31489, 'author': 'jsight', 'author_id': 1432, 'author_profile': 'https://Stackoverflow.com/users/1432', 'pm_score': 2, 'selected': False, 'text': '<p>As far as I know, the only direct ways to do it are:</p>\n\n<ol>\n<li>Commit the txn - Probably not a reasonable option</li>\n<li>Clear the Persistence Context - EntityManager.clear() - This is brutal, but would clear it out</li>\n<li>Copy the object - Most of the time your JPA objects are serializable, so this should be easy (if not particularly efficient).</li>\n</ol>\n'}, {'answer_id': 31553, 'author': 'tonygambone', 'author_id': 3344, 'author_profile': 'https://Stackoverflow.com/users/3344', 'pm_score': 1, 'selected': False, 'text': "<p>If there aren't too many properties in the bean, you might just create a new instance and set all of its properties manually from the persisted bean.</p>\n\n<p>This could be implemented as a copy constructor, for example:</p>\n\n<pre><code>public Thing(Thing oldBean) {\n  this.setPropertyOne(oldBean.getPropertyOne());\n  // and so on\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>Thing newBean = new Thing(oldBean);\n</code></pre>\n"}, {'answer_id': 33041, 'author': 'Andrei', 'author_id': 2718, 'author_profile': 'https://Stackoverflow.com/users/2718', 'pm_score': 5, 'selected': True, 'text': "<p>Unfortunately, there's no way to disconnect one object from the entity manager in the current JPA implementation, AFAIR.</p>\n\n<p>EntityManager.clear() will disconnect <em>all</em> the JPA objects, so that might not be an appropriate solution in all the cases, if you have other objects you do plan to keep connected.</p>\n\n<p>So your best bet would be to clone the objects and pass the clones to the code that changes the objects. Since primitive and immutable object fields are taken care of by the default cloning mechanism in a proper way, you won't have to write a lot of plumbing code (apart from deep cloning any aggregated structures you might have).</p>\n"}, {'answer_id': 898013, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 6, 'selected': False, 'text': '<p>(may be too late to answer, but can be useful for others)</p>\n\n<p>I\'m developing my first system with JPA right now. Unfortunately I\'m faced with this problem when this system is almost complete.</p>\n\n<p>Simply put. Use Hibernate, or wait for JPA 2.0.</p>\n\n<p>In Hibernate, you can use \'session.evict(object)\' to remove one object from session. In <a href="http://jcp.org/en/jsr/detail?id=317" rel="noreferrer">JPA 2.0, <strike>in draft right now</strike>,</a> there is the \'EntityManager.detach(object)\' method to detach one object from persistence context.</p>\n'}, {'answer_id': 1605647, 'author': 'Davide Consonni', 'author_id': 168548, 'author_profile': 'https://Stackoverflow.com/users/168548', 'pm_score': 1, 'selected': False, 'text': '<p>this is quick and dirty, but you can also serialize and deserialize the object.</p>\n'}, {'answer_id': 1808454, 'author': 'trunikov', 'author_id': 220015, 'author_profile': 'https://Stackoverflow.com/users/220015', 'pm_score': -1, 'selected': False, 'text': '<p>I think you can also use method EntityManager.refresh(Object o) if primary key of the entity has not been changed. This method will restore original state of the entity.</p>\n'}, {'answer_id': 2049477, 'author': 'James McMahon', 'author_id': 20774, 'author_profile': 'https://Stackoverflow.com/users/20774', 'pm_score': 4, 'selected': False, 'text': '<p>If you need to detach an object from the EntityManager and you are using Hibernate as your underlying ORM layer you can get access to the <a href="https://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html" rel="noreferrer">Hibernate Session</a> object and use the <a href="https://www.hibernate.org/hib_docs/v3/api/org/hibernate/Session.html#evict%28java.lang.Object%29" rel="noreferrer">Session.evict(Object)</a> method that Mauricio Kanada mentioned above.</p>\n\n<pre><code>public void detach(Object entity) {\n    org.hibernate.Session session = (Session) entityManager.getDelegate();\n    session.evict(entity);\n}\n</code></pre>\n\n<p>Of course this would break if you switched to another ORM provider but I think this is preferably to trying to make a deep copy.</p>\n'}, {'answer_id': 5491768, 'author': 'David Faulstich', 'author_id': 684655, 'author_profile': 'https://Stackoverflow.com/users/684655', 'pm_score': 1, 'selected': False, 'text': '<p>Since I am using SEAM and JPA 1.0 and my system has a fuctinality that needs to log all fields changes, i have created an value object or data transfer object if same fields of the entity that needs to be logged. The constructor of the new pojo is:</p>\n\n<pre><code>    public DocumentoAntigoDTO(Documento documentoAtual) {\n    Method[] metodosDocumento = Documento.class.getMethods();\n    for(Method metodo:metodosDocumento){\n        if(metodo.getName().contains("get")){\n            try {\n                Object resultadoInvoke = metodo.invoke(documentoAtual,null);\n                Method[] metodosDocumentoAntigo = DocumentoAntigoDTO.class.getMethods();\n                for(Method metodoAntigo : metodosDocumentoAntigo){\n                    String metodSetName = "set" + metodo.getName().substring(3);\n                    if(metodoAntigo.getName().equals(metodSetName)){\n                        metodoAntigo.invoke(this, resultadoInvoke);\n                    }\n                }\n            } catch (IllegalArgumentException e) {\n                e.printStackTrace();\n            } catch (IllegalAccessException e) {\n                e.printStackTrace();\n            } catch (InvocationTargetException e) {\n                e.printStackTrace();\n            }\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 5500466, 'author': 'James', 'author_id': 416206, 'author_profile': 'https://Stackoverflow.com/users/416206', 'pm_score': 2, 'selected': False, 'text': '<p>If using <code>EclipseLink</code> you also have the options,</p>\n\n<p>Use the Query hint, <code>eclipselink.maintain-cache"="false</code> - all returned objects will be detached.</p>\n\n<p>Use the <code>EclipseLink</code> <code>JpaEntityManager</code> <code>copy()</code> API to copy the object to the desired depth.</p>\n'}, {'answer_id': 6149959, 'author': 'Warren Crossing', 'author_id': 772748, 'author_profile': 'https://Stackoverflow.com/users/772748', 'pm_score': 0, 'selected': False, 'text': '<p>If you get here because you actually want to pass an entity across a remote boundary then you just put some code in to fool the hibernazi.</p>\n\n<pre><code>for(RssItem i : result.getChannel().getItem()){\n}\n</code></pre>\n\n<p>Cloneable wont work because it actually copies the PersistantBag across. </p>\n\n<p>And forget about using serializable and bytearray streams and piped streams. creating threads to avoid deadlocks kills the entire concept.</p>\n'}, {'answer_id': 12139908, 'author': 'Mehdi', 'author_id': 482628, 'author_profile': 'https://Stackoverflow.com/users/482628', 'pm_score': 5, 'selected': False, 'text': "<p>No matter which JPA implementation you use, Just use <code>entityManager.detach(object)</code> it's now in JPA 2.0 and part of JEE6.</p>\n"}, {'answer_id': 16928294, 'author': 'Chris B', 'author_id': 121732, 'author_profile': 'https://Stackoverflow.com/users/121732', 'pm_score': 1, 'selected': False, 'text': '<p>In JPA 1.0 (tested using EclipseLink) you could retrieve the entity outside of a transaction. For example, with container managed transactions you could do:</p>\n\n<pre><code>public MyEntity myMethod(long id) {\n    final MyEntity myEntity = retrieve(id);\n    // myEntity is detached here\n}\n\n@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)\npublic MyEntity retrieve(long id) {\n    return entityManager.find(MyEntity.class, id);\n}\n</code></pre>\n'}, {'answer_id': 25649132, 'author': 'Roger Mori', 'author_id': 4004848, 'author_profile': 'https://Stackoverflow.com/users/4004848', 'pm_score': 1, 'selected': False, 'text': '<p>Do deal with a similar case I have created a DTO object that extends the persistent entity object as follows:</p>\n\n<pre><code>class MyEntity\n{\n   public static class MyEntityDO extends MyEntity {}\n\n}\n</code></pre>\n\n<p>Finally, an scalar query will retrieve the desired non managed attributes:</p>\n\n<pre><code>(Hibernate) select p.id, p.name from MyEntity P\n(JPA)       select new MyEntity(p.id, p.name) from myEntity P\n</code></pre>\n'}, {'answer_id': 52996053, 'author': 'Abhishek Tripathi', 'author_id': 6517450, 'author_profile': 'https://Stackoverflow.com/users/6517450', 'pm_score': 0, 'selected': False, 'text': '<p>I think there is a way to evict a single entity from EntityManager by calling this</p>\n\n<pre><code>EntityManagerFactory emf;\nemf.getCache().evict(Entity);\n</code></pre>\n\n<p>This will remove particular entity from cache.</p>\n'}, {'answer_id': 68296247, 'author': 'Pradeesh', 'author_id': 6697095, 'author_profile': 'https://Stackoverflow.com/users/6697095', 'pm_score': 0, 'selected': False, 'text': '<p>Im using entityManager.detach(returnObject);\nwhich worked for me.</p>\n'}]
['https://Stackoverflow.com/questions/31446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/506/']