开发者

JPA. Transaction problems while migrating from Hibernate to Eclipselink

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, 开发者_Go百科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.


I think you will find that both approaches actually adhere to the JPA 2 spec. http://download.oracle.com/auth/otn-pub/jcp/persistence-2.0-fr-eval-oth-JSpec/persistence-2_0-final-spec.pdf?e=1318430009&h=d3d726bc7bec224bd8f803aba90d1f13

See Section 3.2.2

3.2.2 Persisting an Entity Instance

A new entity instance becomes both managed and persistent by invoking the persist method on it or by cascading the persist operation. The semantics of the persist operation, applied to an entity X are as follows:

• If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation......

The actual time of the entry into the database is loosely defined. The DB provides the ID for the foreign key so needs to know about the data.

Calling flush may feel bad but it should work in Hibernate too. It writes the data to the DB but does not remove it for the EntityManager so the entity remains attached.

Hope this helps.


I guess that more details will be needed (i.e. post your Entities code), as quite similar code runs in my case without any problem. Just take a look and give a sign if you spot any differences.

It's Glassfish 3.1.1 with EclipseLink.

EJB Code:

@Stateless
public class MyEJB {

    @PersistenceContext
    EntityManager em;

    @TransactionAttribute(value = TransactionAttributeType.REQUIRED)
    public void doSmth() {
        UserData ud = new UserData();
        em.persist(ud);

        Website w = new Website();
        w.setUser(ud);

        em.persist(w);

        System.out.println("!!!!!" + w);
    }   
}

Entity nr 1:

@Entity
public class UserData implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    public Long getId() {
        return id;
    }

    @Override
    public String toString() {
        return "com.entities.UserData[ id=" + id + " ]";
    }
}

Entity nr 2:

@Entity
public class Website implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @OneToOne(optional=false)
    private UserData user;

    public Long getId() {
        return id;
    }

    public void setUser(UserData u){
        user = u;
    }

    public UserData getUser() {
        return user;
    }

    @Override
    public String toString() {
        return "com.entities.Website[ id=" + id + ", " + user +" ]";
    }
}

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
   <persistence-unit name="TransactionsPU" transaction-type="JTA">
      <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
         <jta-data-source>jdbc/__default</jta-data-source>
         <exclude-unlisted-classes>false</exclude-unlisted-classes>
         <properties>
            <property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
         </properties>
   </persistence-unit>
</persistence>

HTH.


I think the problem is probably at your entities. For example, my user entity is something like this:

public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    private String login;
}

Notice the @Id and @Basic annotations. I don't see you using any annotation at UserImpl's attributes.

I suggest you revise your entitys annotations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜