Persisting using hibernate/JPA

I have been working with hibernate/JPA on JBoss for some months now and have one question that I can't find an answer or solution for.

It seems like when creating new entity beans I'm not able to do a query before I at least have called EntityManager.persist(entityBean), or else I get the following error:

TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

An example:

Job job = new Job();
Collection<Task> tasks = job.getTasks();
ActionPlan actionPlan = (ActionPlan) entityManager.createNamedQuery("ActionPlan.findByCommand").
                setParameter("type", RunOperation.Install).getSingleResult();
Task task = Task.getTask(actionPlan);

My problem is that I can't call createNamedQuery without first persisting 'job' (the line that is commented out). ActionPlan has a relation to Job, but the NamedQuery (findByCommand) does not join on Job. What bothers me is that I need to persist Job in order to query the database, when the new created Job is not even interesting in this context.
Moving the call to persist() to the end of the snippet yields the above mentioned error.

I'm aware that the object I'm working on is not persisted, but persisting makes it impossible to rollback if an error occurs.

I believe there is a solution for this, so if someone has the answer I would be very thankful. What am I missing?

Asked by: Edward871 | Posted: 21-01-2022

Answer 1

It seems logical that you cannot query for something which is not in the database yet, no? What you can do is to start using transactions. In a simple case your session will have one transaction which will be open until you close your session. At that moment transaction will be commited and all your changes will be persisted. All you need is to rollback your transaction in case of error.

P.S. Here at the bottom you can find "A typical transaction should use the following idiom".

Session sess = factory.openSession();
Transaction tx;
try {
tx = sess.beginTransaction();
    //do some work
catch (Exception e) {
    if (tx!=null) tx.rollback();
    throw e;
finally {

Answered by: Brianna608 | Posted: 22-02-2022

Answer 2

I am aware that I can't query what has not yet been persisted - and this is not the case either. What I want to find is other Entity beans. Not just the same type, but any type of the Entity beans that I have. And then I get the TransientObjectException.

Did I mention I use JBoss? I believe that using J2EE and JPA the server is in control of my transactions, and the last I want to do is interfere with it?! So for me, besides using requiresNew, etc. I don't mess with transactions - the server does.

Maybe I should move the hibernate tag, because actually I'm using JPA - JBoss uses hibernate. So please relate to that in any code examples.

Answered by: Sawyer104 | Posted: 22-02-2022

Answer 3

Even if you persist object you still can rollback it. Only after invoking flush on EntityManager would case synchronizing to the underlying database.

Answered by: Elian115 | Posted: 22-02-2022

Answer 4

Well I think that the answers and reading up a bit in the Java EE 5Tutorial has given me the right answer.

On the contrary of my belief, persist() does not flush to the database, it only moves the Entity bean to the persisted state. What tricked me is that I noticed that after calling persist the entity actually gets persisted to the database anyway (and maybe the word 'save' in the error message). I took this as flush was called ending my transaction, but if I get themalkolm right, I am still able to rollback - by myself or by the server on an exception.

So the conclusion I make is; persist should just be called, whenever a new entity is made, as long as it is not in relation to another entity already persisted.
Then the transaction is maintained and the server likes you a little bit more ;)

What is left her is that I still don't understand why I am not able to make a query without everything being in a persisted state.

Answered by: Daisy809 | Posted: 22-02-2022

Similar questions

java - HSQLDB and Hibernate/JPA - not persisting to disk?

Something of an novice with HSQL and Hibernate... em.getTransaction().begin(); for (Activity theActivity : activities) { em.persist(theActivity); } em.getTransaction().commit(); em.close(); followed by... EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); System.out.println("QUERY:: " + em.createQuery("SELECT COUNT(*) FROM " +

java - Hibernate/JPA - Foreign Key Index in Object itself

I am currently working on 100+ Java Objects created by someone with no JPA/Hibernate experience into JPA Entities. Their Objects reference other objects based on a Foreign Key in the Class itself. All of the primary Keys are generated outside of the database. For Example (Just to Illustrate) Car @Entity @Table(name="CAR") public class Car { private Integer id; pri...

java - Duplicate a collection of entities and persist in Hibernate/JPA

I want to duplicate a collection of entities in my database. I retreive the collection with: CategoryHistory chNew = new CategoryHistory(); CategoryHistory chLast = (CategoryHistory)em.createQuery("SELECT ch from CategoryHistory ch WHERE = MAX(date)").getSingleResult; List&lt;Category&gt; categories = chLast.getCategories(); chNew.addCategories(categories)// Should be a copy of the categories: OneT...

java - Hibernate/JPA DB Schema Generation Best Practices

I just wanted to hear the opinion of Hibernate experts about DB schema generation best practices for Hibernate/JPA based projects. Especially: What strategy to use when the project has just started? Is it recommended to let Hibernate automatically generate the schema in this phase or is it better to create the database tables manually from earliest phases of the project? Pretending that thr...

java - How to use DAOs with hibernate/jpa?

Assuming the DAO structure and component interaction described below, how should DAOs be used with persistence layers like hibernate and toplink? What methods should/shouldn't they contain? Would it be bad practice to move the code from the DAO directly to the service? For example, let's say that for every model we have a DAO (that may or may not implement a base interface) that looks something like the ...

java - Is it possible to *transform* the type of a polymorphic Hibernate/JPA entity?

UPDATE: after posting, I discovered this is a duplicate of this older question. I have an odd business requirement: my application supports users getting started as "Guests", then later registering to become "Registered" users. Guests are feature-restricted: they are not allowed to access some functionality that ...

java - How to map one class to different tables using hibernate/jpa annotations

I'm currently stuck with what seems to be a very simple problem, but I just can't seem to find a way around: I have 2 identical tables: tbl_creditcard_approved_txns tbl_creditcard_declined_txns The fields in both are identical, and I have one class - Transaction that is used to represent all the appropriate fields in the tables. I'm trying ...

java - HSQLDB and Hibernate/JPA - not persisting to disk?

Something of an novice with HSQL and Hibernate... em.getTransaction().begin(); for (Activity theActivity : activities) { em.persist(theActivity); } em.getTransaction().commit(); em.close(); followed by... EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); System.out.println("QUERY:: " + em.createQuery("SELECT COUNT(*) FROM " +

java - Basic Hibernate/JPA Mapping question

I have to tables I want to map to each other. I want to populate 2 drop down lists: code_r and code_l. When i choose a value from code_r, code_l should display only certain records. In my database I have 2 tables: Table code_r =================== CODE INT LIBELLE VARCHAR And Table code_l =================== ID BIGINT CODE_R_ID INT LIBELLE VAR...

How to map a 2-d matrix in Java to Hibernate/JPA?

I have a legacy database I'm trying to redesign into the 21st century. One of the existing data structures involves a particular class which contains a 2-dimensional matrix of values. If I were to reverse-engineer this class from the database, I'd end up with a series of attributes like: private BigDecimal NODE_1_MATRIX_POS_1_1; private BigDecimal NODE_1_MATRIX_POS_1_2; and so on. Since...

java - @PreUpdate and @Prepersist in hibernate/JPA (using session)

I've hit a blocker adding a fix to an existing project.the main problem is that i'll like to use @Prepersist and @PreUpdate in the POJO to take care of LastModified field (insert and update) using hibernate implementation of JPA with session. Reason ?: That change is required because there is a need to use liquibase 1.9.5 and...

Still can't find your answer? Check out these amazing Java communities for help...

Java Reddit Community | Java Help Reddit Community | Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)