A developer wrote an entity class with the following method:
Private static Logger logger = Logger.getLogger (myLogger);
@PrePersist
@PreUpdate
Public void doA () {
Logger.info (A);
}
@PostPersist
@PostUpdate
Public void doB () {
logger.info (B);
}
What will the log message contain when an application does the following?
1. Begins a transaction
2. Creates the entity
3. Persists the entity
4. Commits the transaction
5. Begins the entity data
6. Modifies the entity data
7. Merges the entity
8. Commits the second transaction
A.
A
A
B
B
B.
A
B
A
B
C.
A
B
B
A
B
D.
The application will throw an exception because multiple lifecycle callback annotations applied to a single method.
For me I think answer should be “D” please test
It’s B. I have tested it.
Here is the Eclipse console output after I have executed listed actions (1 – 8):
Test methods:
/**
* 1. Begins a transaction
* 2. Creates the entity
* 3. Persists the entity
* 4. Commits the transaction
*/
public void testEntityListeners1() {
em.getTransaction().begin();
CustOrder custOrder = new CustOrder();
custOrder.setDescription(“IT Order 3”);
em.persist(custOrder);
em.getTransaction().commit();
}
/**
* 5. Begins the entity data
* 6. Modifies the entity data
* 7. Merges the entity
* 8. Commits the second transaction
*/
public void testEntityListeners2() {
em.getTransaction().begin();
CustOrder custOrder = em.find(CustOrder.class, 3);
custOrder.setDescription(“IT Order 3 (update)”);
em.merge(custOrder);
em.getTransaction().commit();
}
Output:
Mar 27, 2017 2:18:16 PM hr.jpa.certificate.book.model.CustOrder doA
INFO: A
Mar 27, 2017 2:18:17 PM hr.jpa.certificate.book.model.CustOrder doB
INFO: B
Mar 27, 2017 2:18:17 PM hr.jpa.certificate.book.model.CustOrder doA
INFO: A
Mar 27, 2017 2:18:17 PM hr.jpa.certificate.book.model.CustOrder doB
INFO: B
https://docs.jboss.org/hibernate/entitymanager/3.5/reference/en/html/listeners.html
public class LastUpdateListener {
/**
* automatic property set before any database persistence
*/
@PreUpdate
@PrePersist
public void setLastUpdate(Cat o) {
o.setLastUpdate( new Date() );
}
}
Answer B
You can use same method multiple call backs. You cannot use mutiple methods in the same class for same call back.