Standard Java EE environment: JPA + EJB called from JSF beans. Server: glassfish 3.1.1
Code which is developed, tested and deployed with Hibernate as JPA provider, refuses to persist entities with Eclipselink – default JPA provider in glassfish:
Here is the code I call from JSF bean:
@Singleton
@Startup
public class SecurityService {
@PersistenceContext(unitName = "unit01")
private EntityManager em;
@TransactionAttribute(value = TransactionAttributeType.REQUIRED)
public String createNewUser(String login) {
UserImpl newUser = new UserImpl();
newUser.setLogin(login);
em.persist(newUser);
//em.flush() ------> works fine when uncommented
DirectoryImpl userHome = new DirectoryImpl();
userHome.setOwner(newUser);
em.persist(userHome); // Throws exception due to FK violation
//
//
As commented, the code works only if I flush EntityManager after persisting new user, which is obviously wrong. While testing other methods I’ve found that some other changes are flushed to DB only when I shutdown the server.
All above happens in a fresh GF installation, in pure Java EE design without any Spring or whatever frameworks.
Here is my persistence.xml:
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="unit01" transaction-type="JTA">
<jta-data-source>jdbc/Unit01DS</jta-data-source>
<properties>
<property name="eclipselink.logging.level" value="FINE" />
</properties>
</persistence-unit>
</persistence>
Here is how I create data source:
asadmin create-jdbc-connection-pool --datasourceclassname com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource --restype javax.sql.ConnectionPoolDataSource --property "User=u1:Password=xxx:URL=jdbc\:mysql\://localhost/dbname" Unit01DS
asadmin create-jdbc-resource --connectionpoolid Unit01DS jdbc/Unit01DS
That’s all, no other configuration files/options used. So why my code works fine under Hibernate and behaves absolutely differently under Eclipselink? Any ideas?
UPDATE
Further investigation has shown that problem lies somewhere in entity mappings. In my case both mentioned entities (UserImpl and DirectoryImpl) are inherited from a single root class as show below:
@Entity
@Table(name = "ob10object")
@Inheritance(strategy = InheritanceType.JOINED)
public class RootObjectImpl implements RootObject {
private Long id;
@Id
@Column(name = "ob10id", nullable = false)
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
//
UserImpl is a direct subclass of the root entity and has no references to other entities
@Entity
@Table(name = "as10user")
@DiscriminatorValue(value = "AS10")
public class UserImpl extends RootObjectImpl implements User {
private String login;
//
//
A bit more complicated case is DirectoryImpl:
@Entity
@Table(name = "st20directory")
@DiscriminatorValue(value = "ST20")
public class DirectoryImpl extends AbstractStorageNode implements Directory {
// Inside there are also no references to other entities
Where AbstractStorageNode also extends root object:
@Entity
@Table(name = "st10storage_node")
public abstract class AbstractStorageNode extends RootObjectImpl implements StorageNode {
private Set<AbstractStorageNode> childNodes;
private StorageNode parentNode;
private User owner;
@OneToMany(mappedBy = "parentNode")
public Set<AbstractStorageNode> getChildNodes() {
return childNodes;
}
@ManyToOne(targetEntity = AbstractStorageNode.class)
@JoinColumn(name="st10parent", nullable = true)
public StorageNode getParentNode() {
return parentNode;
}
@ManyToOne(targetEntity = UserImpl.class)
@JoinColumn(name = "as10id") // this is FK to `UserImpl` table.
public User getOwner() {
return owner;
}
// Setters omitted
Now here is the generated sql:
// Creating user:
INSERT INTO ob10object (field1, field2, ob10discriminator) VALUES ('v1', 'v2', 'AS10')
SELECT LAST_INSERT_ID()
// Creating Directory:
INSERT INTO ob10object (field1, field2, ob10discriminator) VALUES ('v11', 'v22', 'ST20')
SELECT LAST_INSERT_ID()
INSERT INTO st10storage_node (st10name, as10id, st10parent, ob10id) VALUES ('home', 10, null, 11)
Now I see what happens: eclipselink does not insert data into User table (as10user), causing FK violation in the last query. But still I have no idea why is that happening.
UPDATE 2
Here is the exception:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`dbname`.`st10storage_node`, CONSTRAINT `F_ST10_AS10` FOREIGN KEY (`as10id`) REFERENCES `as10user` (`ob10id`))
Error Code: 1452
So, without the flush you get a constraint error? Please include the exception and stack trace and SQL log, also include how you are mapping the relationship and how you are defining the ids.
Do you have a bi-directional relationship? EclipseLink may be trying to resolve a bi-directional relationship causing your error, you may need to remove a not-null constraint to allow insertion into your table, or define the constraint dependency using a customizer, or fix your bidirectional relationship mapping.
Update
The error is occurring because you have the constraint defined to the child User table not to the parent Root table where the Id is defined. By default EclipseLink deffers the write into secondary tables that have no references to optimize the transaction and avoid database deadlocks.
Technically EclipseLink should be finding the reference to User and not doing this, are you on the latest release, it may have been fixed, otherwise log a bug and vote for it.
You can resolve the issue by using a DescriptorCustomizer and setting the property setHasMultipleTableConstraintDependecy(true) on the Root descriptor.
Also, you seem to have all of your classes sharing the same Root table that seems to only define the id, this is probably not a good idea. You might be better off making Root a @MappedSuperclass and only have table for the concrete subclasses.