EJB 3.0 Persistence – ManyToMany relations or the objectification of the intersection table

I have done a fair bit of Entity Relationship Modeling. It’s one of the things I probably like most about my job. And one of the things in ERD I have been brought up in was: you can start out by modeling Many-to-Many relationships, but in the second stage of your model – when you prepare it for transformation to your technical database design – it is best to ‘resolve’ those nasty many-to-many relationships. Because the database cannot handle them. We cannot have a collection of references stored in a single column or something like that. And quite often there was a good reason for replacing the many-to-many relationship by a so called "intersection entity" as we had to cater for or at least could think of some meaningful characteristics for the relationship itself. How long it lasted or what special type of relationship it was. Or how much it cost. And before the transformation to database design started, we had rid ourselves of the many-to-many’s.

Funnily enough, EJB 3.0 Persistence is again about Entities. Java Classes that are also called POJOs (Plain Old Java Objects) or Domain Classes. An Entity is nothing but a Java Bean – a POJO with some setters and getters – about which we say to the EJB 3.0 EntityManager: it can be persisted. It maps to a table. If we create one, you can Insert into a table. If we look for one, you can Select it from that table. And EJB 3.0 Persistence allows us to specify relations, not just the ones our database can handle, but also the Many-To-Many that it choked on. In this article we will take a brief look at the Many-To-Many relation in EJB 3.0. We will do this using the GlassFish Reference Implementation of EJB 3.0 Persistence and we work strictly outside the container in a stand-alone J2SE application. For more on getting GlassFish installed and starting out with EJB 3.0 Persistence, also see my previous posts Getting Started with EJB 3.0 Persistence out-of-container using the Reference Implementation (GlassFish) and Diving deeper into EJB 3.0 Persistence with GlassFish (RI) – still out of container.

....
EJB 3.0 Persistence - ManyToMany relations or the objectification of the intersection table ejb30 m2m erd

Here you see an example of an ERD, with a Many-To-Many relation. Each Book can have multiple Authors – including people who design the cover, write the foreword and make a guest appearance by write a single chapter. Authors typically will have more than one book they have written. We could argue about the optionality of this relation: can someone be called an Author wihtout having written any books? And can there be a book with now Author? Let’s settle for this definition for now.

The next stage in convention ERD, geared towards database design, would have this many-to-many resolved, usually resulting in an intersection-entity called something like BOOKS_AUTHORS or in this case: Authorship:

EJB 3.0 Persistence - ManyToMany relations or the objectification of the intersection table ejb30 m2m intersection

 

We have found an attribute to, to give some life to the Intersection Entity: Contributor Type which indicates in what capacity the Author has contributed to the Book. We could have add his fee, the time it took to make this contribution etc.

Now however we have an ERD that we can easily turn into a database design and subsequently tables, columns and foreign keys in a relational database. Here is what the database looks like:

EJB 3.0 Persistence - ManyToMany relations or the objectification of the intersection table ejb30 m2m db 

Mapping Java Entities to (Intersection) Tables

When we want to leverage this Database in our Java Application, we have to create the Entities or Domain Objects, typically classes Author and Book. And we have to map those Entities to the underlying database tables. Here is how we do that using EJB 3.0 Persistence.

package nl.amis.als.ejb30;

import java.io.Serializable;

import java.util.Collection;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.ManyToMany;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.CascadeType;


@Entity
@Table(name="ALS_BOOKS")
public class Book implements Serializable {


private Long id;

private String isbn;

private Long publishMonth;

private Long publishYear;

private String title;

private Collection<Author> authors;

public Book() {
}

public Book(Long id, String title) {
this.id = id;
this.title = title;
}

@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(table = @Table(name = "als_authorships"), joinColumns = {
@JoinColumn(name = "bok_id")
}, inverseJoinColumns = {
@JoinColumn(name = "atr_id")
})
public Collection<Author> getAuthors() {
return this.authors;
}

public void setAuthors(Collection<Author> authors) {
this.authors = authors;
}

@Id
@Column(name="ID", nullable=false)
public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

@Column(name="ISBN")
public String getIsbn() {
return isbn;
}

public void setIsbn(String isbn) {
this.isbn = isbn;
}

@Column(name="PUBLISH_MONTH")
public Long getPublishMonth() {
return publishMonth;
}

public void setPublishMonth(Long publishMonth) {
this.publishMonth = publishMonth;
}

@Column(name="PUBLISH_YEAR")
public Long getPublishYear() {
return publishYear;
}

public void setPublishYear(Long publishYear) {
this.publishYear = publishYear;
}

@Column(name="TITLE", nullable=false)
public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

}
 

And its companion, the Author Class:

package nl.amis.als.ejb30;

import java.io.Serializable;

import java.util.Collection;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.ManyToMany;
import javax.persistence.JoinTable;
import javax.persistence.JoinColumn;
import javax.persistence.CascadeType;


@Entity
@Table(name="ALS_AUTHORS")
public class Author implements Serializable {
private String biography;

private String firstName;

private Long id;

private String initials;

private String lastName;

private Collection<Book> books;

public Author() {
}

public Author (Long id) {
this.id = id ;
}

@Column(name="BIOGRAPHY")
public String getBiography() {
return biography;
}

public void setBiography(String biography) {
this.biography = biography;
}

@Column(name="FIRST_NAME")
public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

@Id
@Column(name="ID", nullable=false)
public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

@Column(name="INITIALS")
public String getInitials() {
return initials;
}

public void setInitials(String initials) {
this.initials = initials;
}

@Column(name="LAST_NAME")
public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

@ManyToMany(cascade=CascadeType.ALL)
@JoinTable(table = @Table(name = "als_authorships"), joinColumns = {
@JoinColumn(name = "atr_id")
}, inverseJoinColumns = {
@JoinColumn(name = "bok_id")
})
public Collection<Book> getBooks() {
return this.books;
}
public void setBooks(Collection<Book> books) {
this.books = books;
}

}

Note: in both Entities, we have left out a number of optional properties, for brevity and clarity.

The LibraryService class that provides services for these entities – grantedly a pathetic set of services. In fact: service.

package nl.amis.als.ejb30;

import java.util.Collection;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class LibraryService {
public LibraryService() {

EntityManagerFactory emf =
Persistence.createEntityManagerFactory("pu2");
// create EntityManager
EntityManager em = emf.createEntityManager();
this.setEntityManager(em);
}

private EntityManager _entityManager;

public EntityManager getEntityManager() {
return _entityManager;
}

public void setEntityManager(EntityManager entityManager) {
_entityManager = entityManager;
}

public List<Book> findAllBook() {
return getEntityManager().createQuery("select object(o) from Book o").getResultList();
}

public static void main(String[] args) {
LibraryService libraryService = new LibraryService();
Collection<Book> books = libraryService.findAllBook();
for (Book b : books) {
System.out.println(b.getTitle());
for (Author a: b.getAuthors()) {
System.out.println(" - "+a.getFirstName()+" "+a.getLastName());
}
}
}

}

You can that the LibraryService class references a Persistency Unit called pu2. This refers to a definition in the persistence.xml file, in the classes/META-INF directory. This files looks like this:

<persistence xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="pu2">
<!-- Provider class name is required in Java SE -->
<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
<!-- All persistence classes must be listed -->
<class>nl.amis.als.ejb30.Author</class>
<class>nl.amis.als.ejb30.Book</class>
<properties>
<!-- Provider-specific connection properties -->
<property name="jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>
<property name="jdbc.connection.string" value="jdbc:oracle:thin:@localhost:1521:ORCL"/>
<property name="jdbc.user" value="als"/>
<property name="jdbc.password" value="als"/>
<!-- Provider-specific settings -->
<property name="toplink.logging.level" value="NORMAL"/>
</properties>
</persistence-unit>
</persistence>  

The output of running the LibraryService class is something like 

The Data Warehouse Toolkit
 – Ralph Kimball
 – Ted Husted
Java Tools for eXtreme Programming
 – Richard Hightower
 – Nicholas Lesiecki
J2EE Design and Development
 – Rod Johnson
CSS, Pocket Reference
 – Eric Meyer
JUnit in Action
 – Vincent Massol
 – Ted Husted
Building Oracle XML Applications
 – Steve Muench
Core Java 2, Volume I: Fundamentals
 – Gary Cornell
 – Cay Horstmann
XSLT Cookbook, Solutions and Examples for XML and XSLT Developers
 – Sal Mangano
Core J2EE Patterns: Best Practices and Design Strategies
 – Dan Malks
 – John Crupias
 – Deepak Alur

If we increase the logging – by changing the toplink.logging.level from NORMAL to FINE in the persistence.xml file -, we get a little more insight in what is going on internally:

[TopLink Info]: 2006.01.02 08:13:17.858–ServerSession(27978063)–Thread(Thread[main,5,main])–file:/C:/glassfish/ejb30_se/se1/classes-pu2 login successful
[TopLink Fine]: 2006.01.02 08:13:18.088–ServerSession(27978063)–Connection(5863106)–Thread(Thread[main,5,main])–SELECT ID, PUBLISH_MONTH, PUBLISH_YEAR, ISBN, TITLE FROM ALS_BOOKS

J2EE Design and Development
[TopLink Fine]: 2006.01.02 08:13:18.288–ServerSession(27978063)–Connection(5863106)–Thread(Thread[main,5,main])–SELECT t1.ID, t1.BIOGRAPHY, t1.FIRST_NAME, t1.INITIALS, t1.LAST_NAME FROM als_authorships t0, ALS_AUTHORS t1 WHERE ((t0.bok_id = 5) AND (t1.ID = t0.atr_id))
 – Rod Johnson
CSS, Pocket Reference
[TopLink Fine]: 2006.01.02 08:13:18.298–ServerSession(27978063)–Connection(14900151)–Thread(Thread[main,5,main])–SELECT t1.ID, t1.BIOGRAPHY, t1.FIRST_NAME, t1.INITIALS, t1.LAST_NAME FROM als_authorships t0, ALS_AUTHORS t1 WHERE ((t0.bok_id = 6) AND (t1.ID = t0.atr_id))
 – Eric Meyer
JUnit in Action
[TopLink Fine]: 2006.01.02 08:13:18.298–ServerSession(27978063)–Connection(5863106)–Thread(Thread[main,5,main])–SELECT t1.ID, t1.BIOGRAPHY, t1.FIRST_NAME, t1.INITIALS, t1.LAST_NAME FROM als_authorships t0, ALS_AUTHORS t1 WHERE ((t0.bok_id = 23) AND (t1.ID = t0.atr_id))
 – Vincent Massol
 – Ted Husted
Building Oracle XML Applications
[TopLink Fine]: 2006.01.02 08:13:18.308–ServerSession(27978063)–Connection(14900151)–Thread(Thread[main,5,main])–SELECT t1.ID, t1.BIOGRAPHY, t1.FIRST_NAME, t1.INITIALS, t1.LAST_NAME FROM als_authorships t0, ALS_AUTHORS t1 WHERE ((t0.bok_id = 24) AND (t1.ID = t0.atr_id))
 – Steve Muench
Core Java 2, Volume I: Fundamentals
[TopLink Fine]: 2006.01.02 08:13:18.308–ServerSession(27978063)–Connection(5863106)–Thread(Thread[main,5,main])–SELECT t1.ID, t1.BIOGRAPHY, t1.FIRST_NAME, t1.INITIALS, t1.LAST_NAME FROM als_authorships t0,
ALS_AUTHORS t1 WHERE ((t0.bok_id = 20) AND (t1.ID = t0.atr_id))
 – Gary Cornell
 – Cay Horstmann
XSLT Cookbook, Solutions and Examples for XML and XSLT Developers
[TopLink Fine]: 2006.01.02 08:13:18.318–ServerSession(27978063)–Connection(14900151)–Thread(Thread[main,5,main])–SELECT t1.ID, t1.BIOGRAPHY, t1.FIRST_NAME, t1.INITIALS, t1.LAST_NAME FROM als_authorships t0, ALS_AUTHORS t1 WHERE ((t0.bok_id = 25) AND (t1.ID = t0.atr_id))
 – Sal Mangano
Core J2EE Patterns: Best Practices and Design Strategies
[TopLink Fine]: 2006.01.02 08:13:18.328–ServerSession(27978063)–Connection(5863106)–Thread(Thread[main,5,main])–SELECT t1.ID, t1.BIOGRAPHY, t1.FIRST_NAME, t1.INITIALS, t1.LAST_NAME FROM als_authorships t0, ALS_AUTHORS t1 WHERE ((t0.bok_id = 21) AND (t1.ID = t0.atr_id))
 – Dan Malks
 – John Crupias
 – Deepak Alur
 

We see that GlassFish has correctly interpreted our ManyToMany annotation:

    @ManyToMany(cascade=CascadeType.ALL)
@JoinTable(table = @Table(name = "als_authorships"), joinColumns = {
@JoinColumn(name = "bok_id")
}, inverseJoinColumns = {
@JoinColumn(name = "atr_id")
})
public Collection<Author> getAuthors() {
return this.authors;
}
 

When we ask for the Authors attribute, we are in fact asking for a Collection of Author-entity-instances. These can be retrieved from the ALS_AUTHORS table that the Author entity is mapped to by following the links defined in the JoinTable ALS_AUTHORSHIPS; column BOK_ID in this table points back at our Book’s ID attribute while column ATR_ID refers to the ID attribute of the Author. This results in query we see being executed for getting the authors for each book: join ALS_AUTHORS with ALS_AUTHORSHIPS on ATR_ID = ID and use the BOK_ID in ALS_AUTHORSHIPS to filter on authorships for the current book.

We can of course do the exact same thing from the other point of view: find all authors and for each author all books he or she has worked on. This is driven by the ManyToMany annotation in the Author entity:

    @ManyToMany(cascade=CascadeType.ALL)
@JoinTable(table = @Table(name = "als_authorships"), joinColumns = {
@JoinColumn(name = "atr_id")
}, inverseJoinColumns = {
@JoinColumn(name = "bok_id")
})
public Collection<Book> getBooks() {
return this.books;
}
 

Code that makes use of this relation could look like this:

        Collection<Author> authors = libraryService.getEntityManager().createQuery("select object(o) from Author o").getResultList();;
for (Author a : authors) {
System.out.println(a.getFirstName()+" "+a.getLastName());
for (Book b : a.getBooks()) {
System.out.println(" - "+b.getTitle());
}
}

and a possible outcome would be (note: this data is not actual Amazon data – I have been using this set for testing purposes and as such have messed around with the actual contents; as fas as I know, Ted Husted is not known for his activities in Data Warehouse country):

Richard Hightower
 – Java Tools for eXtreme Programming
 – Optimizing Oracle Performance
Nicholas Lesiecki
 – xxxJava Tools for eXtreme Programming
Ralph Kimball
 – The Data Warehouse Toolkit
 – xxxJava Tools for eXtreme Programming
Steve Muench
 – Building Oracle XML Applications
Rod Johnson
 – J2EE Design and Development
David Eisenberg
 – SVG Very Essentials
Margy Ross
Dan Malks
 – Core J2EE Patterns: Best Practices and Design Strategies
Ted Husted
 – The Data Warehouse Toolkit
 – JUnit in Action
Cary Millsap
Cay Horstmann
 – Core Java 2, Volume I: Fundamentals
Jeff Holt
Gary Cornell
 – Core Java 2, Volume I: Fundamentals
Deepak Alur
 – Core J2EE Patterns: Best Practices and Design Strategies
Budi Kurniawan
 – JavaServer Faces Programming
Sal Mangano
 – XSLT Cookbook, Solutions and Examples for XML and XSLT Developers

Now I am curious what the GlassFish EJB 3.0 EntityManager will do when I try to assign additional authors to a book. And remove them again. Let’s see:

        Collection<Author> authors = libraryService.getEntityManager().createQuery("select object(o) from Author o").getResultList();;
Author husted = null;
for (Author a : authors) {
if ("husted".equalsIgnoreCase(a.getLastName())) {husted = a;}
}
Book jsf = libraryService.getEntityManager().find(Book.class, new Long(22));
System.out.println(jsf.getTitle());
jsf.getAuthors().add(husted);

EntityTransaction tx = libraryService.getEntityManager().getTransaction();
tx.begin();

libraryService.getEntityManager().merge(jsf);
tx.commit();

This results in the following logging:

[TopLink Info]: 2006.01.02 08:36:14.257–ServerSession(14707008)–Thread(Thread[main,5,main])–file:/C:/glassfish/ejb30_se/se1/classes-pu2 login successful
[TopLink Fine]: 2006.01.02 08:36:14.477–ServerSession(14707008)–Connection(10127976)–Thread(Thread[main,5,main])–SELECT ID, BIOGRAPHY, FIRST_NAME, INITIALS, LAST_NAME FROM ALS_AUTHORS
[TopLink Fine]: 2006.01.02 08:36:14.657–ServerSession(14707008)–Connection(4414010)–Thread(Thread[main,5,main])–SELECT ID, PUBLISH_MONTH, PUBLISH_YEAR, ISBN, TITLE FROM ALS_BOOKS WHERE (ID = 22)
JavaServer Faces Programming
[TopLink Fine]: 2006.01.02 08:36:14.667–ServerSession(14707008)–Connection(10127976)–Thread(Thread[main,5,main])–SELECT t1.ID, t1.BIOGRAPHY, t1.FIRST_NAME, t1.INITIALS, t1.LAST_NAME FROM als_authorships t0, ALS_AUTHORS t1 WHERE ((t0.bok_id = 22) AND (t1.ID = t0.atr_id))
[TopLink Fine]: 2006.01.02 08:36:14.698–UnitOfWork(19419092)–Connection(15453627)–Thread(Thread[main,5,main])–INSERT INTO als_authorships (atr_id, bok_id) VALUES (27, 22)

Clearly adding an Author to a Book’s Authors collection and merging (EJB 3.0 equivalent to update or persist changed entity) that Book through the EntityManager results in a proper insert. Let’s see whether removing an Author from a Collection has the same effect.

        tx.begin();
jsf.getAuthors().remove(husted);
libraryService.getEntityManager().merge(jsf);
tx.commit();

And of course it does:

[TopLink Fine]: 2006.01.02 08:41:39.895–UnitOfWork(22897006)–Connection(32380043)–Thread(Thread[main,5,main])–DELETE FROM als_authorships WHERE ((atr_id = 27) AND (bok_id = 22))
 

Of course when the intersection has properties of its own, we cannot get away with (only) the of use ManyToMany. In that case, we have to create an Entity mapped to the Intersection Table. However, we can still use ManyToMany for retrieval and even for manipulation if either the intersection entity’s attributes are optional or values are provided by the database – from triggers or through default values.

Synchronization and Isolation

One of the important things I forgot to mention thusfar is the fact that the Collections that are mapped as ManyToMany relations are isolated from one another. Neither the EntityManager nor the Collections themselves take care of synchronizing each other. That means that when you add an Author to the Book’s Authors collection, no one is adding that Book the Author’s Books collectio

n. You will have to do that yourself! The most direct way is of course adding the Book to the Author’s books collection along with the addition of the Author to the Book’s authors collection. Another way is refreshing the Author after the Book has been merged – and the EntityManager flushed.

Here is a code sample of when the change in the collection at the other end is received. Note that once again I have a misunderstanding with the EntityManager’s ignorance with regard to the identiy of objects. Retrieving the same object – Author Husted for example – in several operations results in different objects! An identity cache in the EntityManager would hopefully prevent these misunderstandings and frustrations!

        Collection<Author> authors = libraryService.getEntityManager().createQuery("select object(o) from Author o").getResultList();;
Author husted = null;
for (Author a : authors) {
if ("husted".equalsIgnoreCase(a.getLastName())) {husted = a;}
}
Book jsf = libraryService.getEntityManager().find(Book.class, new Long(22));
System.out.println(jsf.getTitle());
jsf.getAuthors().add(husted);

System.out.println("Does Husted's books collection contain the JSF book now (after adding Husted to the JSF Book)? "+(findBookInCollection(jsf, husted.getBooks())?"Yes it does":"No it does not"));
EntityTransaction tx = libraryService.getEntityManager().getTransaction();

tx.begin();
husted = libraryService.getEntityManager().find(Author.class, new Long(27));
System.out.println("Does Husted's books collection contain the JSF book now (after reading Husted from the database)? "+(findBookInCollection(jsf, husted.getBooks())?"Yes it does":"No it does not"));
libraryService.getEntityManager().merge(jsf);
tx.commit();
System.out.println("Does Husted's books collection contain the JSF book now (after merging and committin the JSF Book)? "+(findBookInCollection(jsf, husted.getBooks())?"Yes it does":"No it does not"));
tx.begin();
husted = libraryService.getEntityManager().find(Author.class, new Long(27));
libraryService.getEntityManager().refresh(husted);
System.out.println("Does Husted's books collection - after refreshing Husted - contain the JSF book now? "+(findBookInCollection(jsf, husted.getBooks())?"Yes it does":"No it does not"));
husted = libraryService.getEntityManager().find(Author.class, new Long(27));
libraryService.getEntityManager().flush();
libraryService.getEntityManager().refresh(husted);
System.out.println("Does Husted's books collection - after flushing and refreshing - contain the JSF book now? "+(findBookInCollection(jsf, husted.getBooks())?"Yes it does":"No it does not"));


jsf.getAuthors().remove(husted);
libraryService.getEntityManager().merge(jsf);
tx.commit();

The output of this piece of code looks like this:

[TopLink Fine]: 2006.01.02 04:44:06.294--ServerSession(27978063)--Connection(2830910)--Thread(Thread[main,5,main])--SELECT ID, BIOGRAPHY, FIRST_NAME, INITIALS, LAST_NAME FROM ALS_AUTHORS
JavaServer Faces Programming
[TopLink Fine]: 2006.01.02 04:44:06.324--ServerSession(27978063)--Connection(7858936)--Thread(Thread[main,5,main])--SELECT t1.ID, t1.PUBLISH_MONTH, t1.PUBLISH_YEAR, t1.ISBN, t1.TITLE FROM als_authorships t0, ALS_BOOKS t1 WHERE ((t0.atr_id = 27) AND (t1.ID = t0.bok_id))
Does Husted's books collection contain the JSF book now (after adding Husted to the JSF Book)? No it does not
Does Husted's books collection contain the JSF book now (after reading Husted from the database)? No it does not
[TopLink Fine]: 2006.01.02 04:44:06.374--UnitOfWork(18930675)--Connection(17818297)--Thread(Thread[main,5,main])--INSERT INTO als_authorships (atr_id, bok_id) VALUES (27, 22)
Does Husted's books collection contain the JSF book now (after merging and committin the JSF Book)? No it does not
[TopLink Fine]: 2006.01.02 04:44:06.394--ServerSession(27978063)--Connection(2830910)--Thread(Thread[main,5,main])--SELECT ID, BIOGRAPHY, FIRST_NAME, INITIALS, LAST_NAME FROM ALS_AUTHORS WHERE (ID = 27)
Does Husted's books collection - after refreshing Husted - contain the JSF book now? No it does not
[TopLink Fine]: 2006.01.02 04:44:06.394--UnitOfWork(27109735)--Connection(15354046)--Thread(Thread[main,5,main])--SELECT ID, BIOGRAPHY, FIRST_NAME, INITIALS, LAST_NAME FROM ALS_AUTHORS WHERE (ID = 27)
[TopLink Fine]: 2006.01.02 04:44:06.404--UnitOfWork(27109735)--Connection(15354046)--Thread(Thread[main,5,main])--SELECT t1.ID, t1.PUBLISH_MONTH, t1.PUBLISH_YEAR, t1.ISBN, t1.TITLE FROM als_authorships t0, ALS_BOOKS t1 WHERE ((t0.atr_id = 27) AND (t1.ID = t0.bok_id))
Does Husted's books collection - after flushing and refreshing - contain the JSF book now? Yes it does
[TopLink Fine]: 2006.01.02 04:44:06.404--UnitOfWork(27109735)--Connection(15354046)--Thread(Thread[main,5,main])--SELECT t1.ID, t1.BIOGRAPHY, t1.FIRST_NAME, t1.INITIALS, t1.LAST_NAME FROM als_authorships t0, ALS_AUTHORS t1 WHERE ((t0.bok_id = 22) AND (t1.ID = t0.atr_id))
[TopLink Fine]: 2006.01.02 04:44:06.404--UnitOfWork(27109735)--Connection(15354046)--Thread(Thread[main,5,main])--SELECT t1.ID, t1.PUBLISH_MONTH, t1.PUBLISH_YEAR, t1.ISBN, t1.TITLE FROM als_authorships t0, ALS_BOOKS t1 WHERE ((t0.atr_id = 27) AND (t1.ID = t0.bok_id))
[TopLink Fine]: 2006.01.02 04:44:06.414--UnitOfWork(27109735)--Connection(15354046)--Thread(Thread[main,5,main])--SELECT t1.ID, t1.BIOGRAPHY, t1.FIRST_NAME, t1.INITIALS, t1.LAST_NAME FROM als_authorships t0, ALS_AUTHORS t1 WHERE ((t0.bok_id = 22) AND (t1.ID = t0.atr_id))
 

Note: if you retrieve an Entity inside a transaction, you can still use that Entity outside the transaction, but it has become ‘detached’ when the transaction ended. Detached means it is no longer in a managed state which means that it cannot be refreshed anymore. So the following does not work:

        EntityTransaction tx = libraryService.getEntityManager().getTransaction();

tx.begin();
husted = libraryService.getEntityManager().find(Author.class, new Long(27));
System.out.println("Does Husted's books collection contain the JSF book now (after reading Husted from the database)? "+(findBookInCollection(jsf, husted.getBooks())?"Yes it does":"No it does not"));
libraryService.getEntityManager().merge(jsf);
tx.commit();
libraryService.getEntityManager().refresh(husted);
 

The last line attempts to refresh an Entity that was acquired inside the transaction that has already been  committed. This results in an exception:

Exception in thread "main" javax.persistence.TransactionRequiredException: 
Exception Description: No transaction is currently active
at oracle.toplink.essentials.internal.ejb.cmp3.transaction.EntityTransactionWrapper.throwCheckTransactionFailedException(EntityTransactionWrapper.java:58)
at oracle.toplink.essentials.internal.ejb.cmp3.transaction.base.EntityTransactionWrapper.checkForTransaction(EntityTransactionWrapper.java:59)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.checkForTransaction(EntityManagerImpl.java:392)
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.refresh(EntityManagerImpl.java:223)
at nl.amis.als.ejb30.LibraryService.main(LibraryService.java:77)

To my surprise – and this really seems a bug as it is a direct contradiction of the specification – the following code fails to:

 tx.begin();
jsf.s etTitle(jsf.getTitle()+"?");
libraryService.getEntityManager().merge(jsf);
libraryService.getEntityManager().refresh(jsf);
tx.commit();
 

The exception thrown:

Exception in thread "main" java.lang.IllegalArgumentException: Can not refresh not managed object: nl.amis.als.ejb30.Book@18aab40.
at oracle.toplink.essentials.internal.ejb.cmp3.base.EntityManagerImpl.refresh(EntityManagerImpl.java:225)
at nl.amis.als.ejb30.LibraryService.main(LibraryService.java:76)

Line 76 is the line where we have the EntityManager refresh jsf. That should not be a problem. Well, it seems to indicate that refresh can never be used…  

Resources

Source code for the Library Classes and Database Objects:  

Java EE 5 -Step by Step – Filippo Diotalevi – December 2005 – A real low threshold introduction into EJB 3.0 Inside the container using GlassFish

EJB 3.0 – Refreshing entity with values populated from database triggers by Raghu Kodali (14th October 2005) – The issue I have been thinking about a lot and indeed, Raghu writes that if your entity has attributes whose values are provided by the database, either through default values or via Database Triggers, you have to have the persist operation followed by a flush (to force the insert operation) and a refresh (to get the latest values back from the database). Now I am hoping I can build that behavior into an extended EntityManager implementation.

 

J2EE Persistence Productivity with Choice Doug Clarke Principal Product Manager OracleAS TopLink  (Presentation 2004)

12 Comments

  1. Peter June 7, 2008
  2. mario kofler December 13, 2007
  3. Jim McCollom October 23, 2007
  4. jeroen dijkmeijer October 3, 2007
  5. Iner October 2, 2007
  6. Thomas September 23, 2007
  7. Roger Allen February 15, 2007
  8. Lucas Jellema October 16, 2006
  9. Chris June 22, 2006
  10. John April 14, 2006
  11. Lucas Jellema January 2, 2006
  12. Marcello January 2, 2006