@EmbeddedID - JPA

Hello!!
I'm trying to map a relationship 1-N (Product(1)/Item(N)) and I'm getting an error when i
insert the product.
Error: Cannot insert the value NULL into column ITEM_PRODUCT.CD_PRODUCT.
It sounds like I'm missing something, specially in my composite key.
Please, could someone take a look and try to identify anything wrong?
I did many tests already, but... :(( nooo good
Code:
Produto.class (Product)
@Id
@Column(name = "CD_PRODUTO", nullable = false)
@SequenceGenerator(name="SqProduto",sequenceName="SQ_PRODUTO", allocationSize=20)
@GeneratedValue(strategy=javax.persistence.GenerationType.SEQUENCE, generator="SqProduto")
private Long cdProduto;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "produto")
private java.util.Collection <entity.ItemProduto> itemProdutoCollection;
ItemProduto.class (ItemProduct)
@EmbeddedId
protected ItemProdutoPK ItemProdutoPK;
@JoinColumn(name = "CD_PRODUTO", referencedColumnName = "CD_PRODUTO", insertable=false, updatable=false)
@ManyToOne
private Produto produto;
ItemProdutoPK.class
@Id
@Column(name = "CD_PRODUTO", nullable = false)
private int cdProduto;
@Id
@Column(name = "CD_ITEM_PRODUTO", nullable = false)
@SequenceGenerator(name="SqItemProduto",sequenceName="SQ_ITEM_PRODUTO", allocationSize=20)
@GeneratedValue(strategy=javax.persistence.GenerationType.SEQUENCE, generator="SqItemProduto")
private int cdItemProduto;
Test.class
Produto p = new Produto();
p.setDsProd("p1");
ItemProduto ip = new ItemProduto();
ip.setDsItem("item1");
ip.setProduto(p);
p.getItemProdutoCollection().add(ip);
ip = new ItemProduto();
ip.setDsItem("item2");
ip.setProduto(p);
p.getItemProdutoCollection().add(ip);
em.persist(p); // ERROR
Thanks a lot
!_Let's share ideas_!

Instead of @EmbeddedId, I'm now using @IdClass and it is working.
Now my code is like that:
Produto.class (Product - no changes)
@Id
@Column(name = "CD_PRODUTO", nullable = false)
@SequenceGenerator(name="SqProduto",sequenceName="SQ_PRODUTO", allocationSize=20)
@GeneratedValue(strategy=javax.persistence.GenerationType.SEQUENCE, generator="SqProduto")
private Long cdProduto;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "produto")
private java.util.Collection <entity.ItemProduto> itemProdutoCollection;
ItemProduto.class (Item Product)
@IdClass(ItemProdutoPK.class)
public class ItemProduto implements Serializable {
@Id
@Column(name="CD_PRODUTO", nullable = false, insertable = false,
updatable = false)
private Long cdProduto;
@Id
@Column(name="CD_ITEM_PRODUTO", nullable = false)
@SequenceGenerator(name="SqItemProduto",sequenceName="SQ_ITEM_PRODUTO", allocationSize=20)
@GeneratedValue(strategy=javax.persistence.GenerationType.SEQUENCE, generator="SqItemProduto")
private Long cdSubgr;
@ManyToOne
@JoinColumn(name = "CD_PRODUTO", referencedColumnName = "CD_PRODUTO")
private Produto produto;
ItemProdutoPK.class
public Long cdProduto;
public Long cdItemProduto;
Test.class -> the same.
But, I still don't undertand what is wrong in the other way I did.
Could someone identify anything?
Thanks!!!
!_Let's share ideas_!

Similar Messages

  • JPA: Error "entity is detached" when executing a query

    Hi experts,
    I have two database tables with a foreign key constraint and generated JPA-entities for them:
    @Entity
    public class Verdeck implements Serializable {
         @EmbeddedId
         private VerdeckPK pk;
         @Column(name="ID_VERDECK")
         private String idVerdeck;
         @OneToMany(mappedBy="verdeck")
         @PersistenceContext
         private Set<Uzsb> uzsbCollection;
    @Embeddable
    public class UzsbPK implements Serializable {
         @Column(name="ID_UZSB")
         private String idUzsb;
         @Column(name="ID_PROJECT")
         private BigDecimal idProject;
    Furthermore I have a SessionBean implementing a query in one of its business methods:
    @WebMethod(operationName="getVerdeckData", exclude=false)
    public List<Verdeck> getVerdeckData (@WebParam(name="searchkey")
         BigDecimal searchkey){
         Query q = em.createQuery("SELECT v FROM Verdeck v WHERE v.pk.idProject = :searchkey")
              .setParameter("searchkey", searchkey);
              return q.getResultList();
    When calling the method via WebService-Navigator I get this error:
    "com.sap.engine.services.webservices.espbase.server.additions.exceptions.ProcessException: The relationship >>uzsbCollection<< of entity (com.karmann.r57schraub.jpa.Verdeck(idProject=57, idIntern=v1))cannot be loaded because the entity is detached"
    (idProject / idIntern) is the composed key of "Verdeck" and (57 / v1) is a concrete value for this key in the database table.
    If required I could give you classes VerdeckPK and UzsbPK as well.
    Could you please explain what I'm doing wrong?
    Thanks for each hint,
    Christoph

    Hi Vladimir,
    thank you for this hint! Especially for the article which provides the neccessary knowledge in background.
    But using FetchType.EAGER does not solve my problem. I get a runtime error. In defaultTrace I get the following message
    SAXException2: A cycle is detected in the object graph. This will cause infinitely deep XML: com.karmann.r57schraub.jpa.Verdeck@f9ac24 -> com.karmann.r57schraub.jpa.Uzsb@1f2a70 -> com.karmann.r57schraub.jpa.Verdeck@f9ac24]->com.sun.istack.SAXException2: A cycle is detected in the object graph. This will cause infinitely deep XML: com.karmann.r57schraub.jpa.Verdeck@f9ac24 -> com.karmann.r57schraub.jpa.Uzsb@1f2a70 -> com.karmann.r57schraub.jpa.Verdeck@f9ac24#
    I already checked the records in my tables. There does not seem to be any cycle. Here's my test data:
    VERDECK
    ID_PROJECT    ID_INTERN     ID_VERDECK
    57                    v1                  vext1
    57                    v2                  vext2
    UZSB
    ID_PROJECT ID_UZSB ID_INTERN TYP_UZSB
    57 ls1 v1 <null>
    57 rs1 v1 <null>
    57 sd1 v1 <null>
    57 ls2 v2 <null>
    57 rs2 v2 <null>
    57 sd2 v2 <null>
    Do you have any more idea?
    Regards,
    Christoph

  • Out of memory error importing a JPA Entity in WebDynpro Project

    Hi All!
    We are having problems importing JPA entities in a WebDynPro project, this is our escenario.
    We have two entities, entity A that has a ManyToOne relationship with entity B and at the same time entity B has a OneToMany relationship with entity A. When in the controller context we try to create a node usign a model binding to Entity A we got an Out of memory error from NetWeaver DS. Trying to figure out the problem we identified that in the model that we imported we got the following.
    Entity A
        Entity B
            Entity A
               Entity B
                  and so on....... without and end
    What are we doing wrong? Or how can we avoid these behavior?
    Regards,

    Hi Kaylan:
    Thanks for your reply. You are rigth about the error that we are getting. This is our scenario.
    We have a ejb that in some of his method uses the entity Lote, and this entity has a relationship with entity Categoria. When we import the EJB using the model importer netweaver imports the EJB methods and the entities that they use.
    So after doing this besides the ejb's methods we got these two entities that are the ones that are generating the error, when we try to create a context node using the Categoria entity.
    @Entity
    @Table(name="TB_LOTE")
    public class Lote implements Serializable {
         @EmbeddedId
         private Lote.PK pk;
         @ManyToOne
         @JoinColumn(name="CO_CATEGORIALOTE")
         private Categoria coCategorialote;
         @Embeddable
         public static class PK implements Serializable {
              @Column(name="CO_LOTE")
              private String coLote;
              @Column(name="CO_ORDENFABRICACION")
              private String coOrdenfabricacion2;
                   ^ this.coOrdenfabricacion2.hashCode();
    @Entity
    @Table(name="TB_CATEGORIA")
    public class Categoria implements Serializable {
         @Id
         @Column(name="CO_CATEGORIA")
         private String coCategoria;
         @OneToMany(mappedBy="coCategorialote")
         private Set<Lote> tbLoteCollection;
    Regards,
    Jose Arango

  • TopLink Grid: NullPointerException for @EmbeddedId

    Hi,
    I need short help with TopLink Grid (111130). I am trying to use L2 caching for the following entity:
    @Entity
    @Table(name = "T_CONFIGURATION")
    @OptimisticLocking(type = OptimisticLockingType.VERSION_COLUMN)
    @CacheInterceptor(CoherenceInterceptor.class)
    public class ConfigurationDBVO implements Serializable {
    @EmbeddedId
    protected ConfigurationDBKey key = new ConfigurationDBKey();
    @Column(name = "ATTRIBUTE_VALUE")
    private String attributeValue;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumns(value = {@JoinColumn(name = "CONFIG_TYPE", referencedColumnName = "CONFIG_TYPE")})
    private ConfigurationTypeDBVO configurationType;
    @Version
    private int version;
    /* getters and setters */
    @Embeddable
    public class ConfigurationDBKey implements Serializable {
    @Column(name = "ATTRIBUTE_NAME")
    private String attributeName;
    @Column(name = "CONFIGURATION_ID")
    private String configurationID;
    /* getters and setters */
    I receive the following NullPointerException when trying to execute simple JPQL (SELECT c FROM ConfigurationDBVO c WHERE c.configurationType.configType = :configurationType ORDER BY c.key.configurationID):
    java.lang.NullPointerException
    at org.eclipse.persistence.descriptors.CMPPolicy.createPrimaryKeyInstance(CMPPolicy.java:337)
    at oracle.eclipselink.coherence.integrated.internal.cache.CoherenceCacheHelper.getCoherenceKey(CoherenceCacheHelper.java:615)
    at oracle.eclipselink.coherence.integrated.internal.cache.CoherenceCacheHelper.getFromCoherence(CoherenceCacheHelper.java:91)
    at oracle.eclipselink.coherence.integrated.cache.CoherenceInterceptor.acquireLock(CoherenceInterceptor.java:104)
    at org.eclipse.persistence.internal.identitymaps.IdentityMapManager.acquireLock(IdentityMapManager.java:127)
    at org.eclipse.persistence.internal.sessions.IdentityMapAccessor.acquireLock(IdentityMapAccessor.java:88)
    at org.eclipse.persistence.internal.sessions.IdentityMapAccessor.acquireLock(IdentityMapAccessor.java:79)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:642)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildWorkingCopyCloneNormally(ObjectBuilder.java:583)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObjectInUnitOfWork(ObjectBuilder.java:552)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:492)
    at org.eclipse.persistence.internal.descriptors.ObjectBuilder.buildObject(ObjectBuilder.java:444)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.buildObject(ObjectLevelReadQuery.java:635)
    at org.eclipse.persistence.queries.ReadAllQuery.registerResultInUnitOfWork(ReadAllQuery.java:838)
    at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:464)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:997)
    at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:675)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:958)
    at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:432)
    at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1021)
    at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2898)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1225)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1207)
    at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1181)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:453)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getResultList(EJBQueryImpl.java:681)
    at *.ConfigurationACSImpl.searchConfigurations(ConfigurationACSImpl.java:*)
    It seems that EclipseLink is not able to extract correct fields mapping information for keys since the key fields are inside the EmbeddedId object.
    Is there anything wrong in entity mappings (I was able to solve my problem with patching of EclipseLink)?
    Thanks in advance
    Denis

    Hi Gordon,
    Thanks for your answer. Actually, I used my own 1-line patch like this (is it wrong?):
    org.eclipse.persistence.descriptors.CMPPolicy
    for (int index = 0; index < pkElementArray.length; index++) {
    KeyElementAccessor accessor = pkElementArray[index];
    DatabaseMapping mapping = getDescriptor().getObjectBuilder().getMappingForAttributeName(accessor.getAttributeName());
    // begin of patch
    if (mapping == null) {
    mapping = accessor.getMapping();
    // end of patch
    Object fieldValue = null;
    if (mapping.isDirectToFieldMapping()) {
    Thanks in advance
    Denis

  • [JPA] Primary key = Foreign key = Failure.

    Hello:
    I've a question regarding the Java Persistence API and a DB design which I'm facing just now. I'm making JPA entities based on a DB schema which is already created. Although sometimes it's not a good idea, I'm going to use a simplified example so you can understand it easily and help me (if you want, of course).
    Let's suppose that I've a table of discs (called "disc", built into a class as "Disc.class") and another one of used discs (called "disc_used", built as "DiscUsed.class"). The first one employs a composite key formed by columns "key1" and "key2". The second one employs the same primary key (conceptually, not physically) which, at the same time, is foreign key respect to the first table.
    I've used the @EmbeddedId annotation on the first case and built a class for the composite key (called "DiscPK.class"). I've done the same task for the second table (calling it "DiscUsedPK.class"). I also have added the corresponding mappings between both classes (of type @OneToOne). This design pattern works fine when employing "Disc.class", but not "DiscUsed.class". I've came to the conclusion that it's because of using the same fields to make an @EmbeddedId and map the @OneToOne relation.
    I've been taking a deep look to the possible annotations which JPA offers, but I've not found anything useful.
    In the past I faced another problem with JPA and composite keys, which made me come to the conclusion that it was my DB design what was faulty (I was combining an auto-numerical field with others to make a composite key, which helped me to understand the logic but was absurd and against the relational logic). May it be a similar misconception on the DB design? I mean, since both tables represent different concepts (discs and used discs), each one with their own attributes (columns), Should the second table use its own auto-numerical primary key instead of re-use the foreign key? Would it be the right approach according to the relational logic?
    Obviously, modifying the original DB by hand and adding its own primary key, it works flawless. However I still need to know the truth (other-way I won't be able to sleep :P ).
    Thank you for your help and interest.

    gimbal2: I'm really sorry, but I didn't get any e-mail notification about your message :S . After having looked for help on several places on the Internet I finally decided not to employ exactly the same columns for a primary key if they were already being employed by a foreign key. The answer from javaUserMuser has also left this matter clarified to me. Thanks for your time also ;) .
    javaUserMuser: I thought that was a problem from my implementation. If it's a common case, then I guess that I did right choosing the easy "path" for one time :) . I agree with you, it's a big frustration. But since I depend on the JPA for my projects, I'll try to set my mind to avoid always this match and employ another primary key instead. Thank you a lot for your explanation :D .

  • JPA - One to Many persistence issue

    Hi All,
    We are facing an issue with one to many relationship persistence using JPA.
    We have a one to many relationship between Company and Personnel. When A personnel is created, the company(the parent in the relationship) is selected and that needs to be persisted along with the new Personnel Entity
    Find below the Entity Definitions and the code snippet to persist the Entity into the database.
    Entity - Company:
    @OneToMany(mappedBy = "company", cascade=CascadeType.ALL, fetch = javax.persistence.FetchType.EAGER)
    private Collection<Personnel> personnelCollection;
    Entity Personnel:
    @ManyToOne(optional = true)
    private Company company;
    public ErrorCode createAndAssignPersonnel(String personnelName, String company, String email, String title, String user)
    PersonnelPK personnelPK = new PersonnelPK(personnelName, this.appInfoEJB.getSiteId());
    Personnel personnel = new Personnel(personnelPK);
    personnel.setEmail(email);
    personnel.setTitle(title);
    CompanyPK companyPK = new CompanyPK(company, this.appInfoEJB.getSiteId());
    Company companyObj = this.companyEJB.find(companyPK);
    //Double Wiring the personnel and company records
    companyObj.getPersonnelCollection().add(personnel);
    personnel.setCompany(companyObj);
    //Running merge on the parent entity
    em.merge(companyObj);
    return ErrorCode.OK;
    The personnel entity is being persisted into the database but the company is not getting associated with it. (The company value remains blank)
    We are using the Toplink JPA Implementation with Glassfish application server. Any pointers would be greatly appreciated.
    Thanks and Regards,
    GK
    Edited by: user12055063 on Oct 13, 2009 10:05 AM
    Edited by: user12055063 on Oct 13, 2009 10:05 AM

    Hi All,
    Since PERSONNEL and COMPANY both had the SITEID column, we renamed the column in both tables to check if that solves the issue. However, a null company value is still being persisted into the database.
    Find below the altered schema:
    CREATE TABLE COMPANY
    COMPANYNAME VARCHAR(255) NOT NULL,
    COMPANYSITEID VARCHAR (255) NOT NULL,
    PARENTNAME VARCHAR(255),
    PARENTSITEID VARCHAR(255),
    ADDRESS VARCHAR(255),
    PRIMARY KEY (COMPANYNAME, COMPANYSITEID),
    FOREIGN KEY (PARENTNAME, PARENTSITEID) REFERENCES COMPANY (COMPANYNAME, COMPANYSITEID)
    CREATE TABLE PERSONNEL
    PERSONNELNAME VARCHAR(255) NOT NULL,
    PERSONNELSITEID VARCHAR(255) NOT NULL,
    COMPANY VARCHAR(255),
    EMAIL VARCHAR(255),
    TITLE VARCHAR(255),
    PRIMARY KEY (PERSONNELNAME, PERSONNELSITEID)
    ALTER TABLE PERSONNEL
    ADD CONSTRAINT PERCOMPANYCONS FOREIGN KEY (COMPANY, PERSONNELSITEID) REFERENCES COMPANY (COMPANYNAME, COMPANYSITEID);
    The corresponding entity classes are as follows:
    Personnel:
    public class Personnel implements Serializable {
        private static final long serialVersionUID = 1L;
        @EmbeddedId
        protected PersonnelPK personnelPK;
        @Column(name = "EMAIL")
        private String email;
        @Column(name = "TITLE")
        private String title;
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "personnel", fetch = FetchType.EAGER)
        private Collection<Deliverynote> deliverynoteCollection;
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "personnel", fetch = FetchType.EAGER)
        private Collection<Microreader> microreaderCollection;
        @JoinColumns({@JoinColumn(name = "COMPANY", referencedColumnName = "COMPANYNAME"), @JoinColumn(name = "PERSONNELSITEID", referencedColumnName = "COMPANYSITEID", insertable = false, updatable = false)})
        @ManyToOne
        private Company company;
        public Personnel() {
    Company:
    public class Company implements Serializable {
        private static final long serialVersionUID = 1L;
        @EmbeddedId
        protected CompanyPK companyPK;
        @Column(name = "ADDRESS")
        private String address;
        @OneToMany(mappedBy = "company", fetch = FetchType.EAGER)
        private Collection<Company> companyCollection;
        @JoinColumns({@JoinColumn(name = "PARENTNAME", referencedColumnName = "COMPANYNAME"), @JoinColumn(name = "PARENTSITEID", referencedColumnName = "COMPANYSITEID")})
        @ManyToOne(fetch = FetchType.EAGER)
        private Company company;
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "company", fetch = FetchType.EAGER)
        private Collection<Credential> credentialCollection;
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "company", fetch = FetchType.EAGER)
        private Collection<Personnel> personnelCollection;
        @OneToMany(cascade = CascadeType.ALL, mappedBy = "company", fetch = FetchType.EAGER)
        private Collection<Entityobject> entityobjectCollection;
        public Company() {
        }...The code for persisting the personnel record is as follows:
      public ErrorCode createAndAssignPersonnel(String personnelName, String company, String email, String title, String user)
            Personnel personnel = new Personnel(new PersonnelPK(personnelName, this.appInfoEJB.getSiteId()));
            personnel.setEmail(email);
            personnel.setTitle(title);
            Company companyObj = this.companyEJB.find(new CompanyPK(company, this.appInfoEJB.getSiteId()));
            personnel.setCompany(companyObj);
            companyObj.getPersonnelCollection().add(personnel);
            //em.merge(companyObj);
            em.persist(personnel);
            em.flush();
            return ErrorCode.OK;
        }The SQL queries internally generated as as follows:
    INSERT INTO PERSONNEL (TITLE, EMAIL, PERSONNELSITEID, PERSONNELNAME) VALUES (?, ?, ?, ?)
    bind => [, , JackOnSite, Tester]
    In this case, the company field is not even added in the query.
    On deleting the updatable, insertable attributes from the JoinColumns annotation as follows:
    @JoinColumns({@JoinColumn(name = "COMPANY", referencedColumnName = "COMPANYNAME"), @JoinColumn(name = "PERSONNELSITEID", referencedColumnName = "COMPANYSITEID" )})
    @ManyToOne
    private Company company;The following query is generated:
    Local Exception Stack:
    Exception [TOPLINK-4002] (Oracle TopLink Essentials - 2.0 (Build b58g-fcs (09/07/2007))): oracle.toplink.essentials.exceptions.DatabaseException
    Internal Exception: java.sql.SQLSyntaxErrorException: Column name 'PERSONNELSITEID' appears more than once times in the column list of an INSERT statement.
    Error Code: -1
    Call: INSERT INTO PERSONNEL (TITLE, EMAIL, COMPANY, PERSONNELSITEID, PERSONNELSITEID, PERSONNELNAME) VALUES (?, ?, ?, ?, ?, ?)
    bind => [, , Test New, JackOnSite, JackOnSite, Sesi]
    Note that in this case, the company is being inserted into the query. However, the PERSONNELSITEID appears twice.
    The company table has a foreign key reference to itself and we have tried testing this use case by dropping that constraint without any success.
    We would greatly appreciate any pointers/suggestions.
    Thanks and Regards,
    GK

  • JPA uniqueness constraint on columns

    Hi all,
    I have a very simple data structure which has
    - the key (String) of another data class
    - a Date (using TemporalType.DATE)
    - an integer value
    but the combination of the timestamp and the key makes for a unique identifier. I could quite easily add an additional 4th @Column into my @Entity that is my @Id, but I'd rather investigate how JPA can help me setup a custom @Id that is the combination of the key and the timestamp value. It would be good to be able to let the database manage the uniqueness, instead of me having to programmatically handle (and check) it in JPA-QL queries.
    Is this a classic case of @EmbeddedId or @IdClass? If so, it seems like an awful lot of boilerplate code to achieve what I want. Is what I am proposing even recommended? Is there perhaps another way to achieve uniqueness for the combination of these two columns?

    In general I would recommend using a generated Id, but yes, your example is a case for using an @EmbeddedId or @IdClass.
    See,
    http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Composite_Primary_Keys
    -- James : http://www.eclipselink.org

  • SAP-JPA changes version of unchanged entities

    Hi all:
    We are having a problem with an application that we developed using Sap NetWeaver 7.1 . We are having optimisticlock exception in some of the transactions that we have in the application, checking this situation we found that SAP-JPA is updating the version field for entities that we haven't change. Why is this happening?

    Hi Adrian:
    I'm sending the following:
    1. The ejb's method that we are using to execute the query.
    2. The query.
    3. The entities that are part of the query, if you need I can send you the related entities.
    This is the method that we are calling from webDynpro.
    @TransactionAttribute(value=TransactionAttributeType.NOT_SUPPORTED)
    public List<Object> buscarOrdenesFabricacion(String codigoLote){
         ArrayList<Object> listaParametros = new ArrayList<Object>();
         listaParametros.add(codigoLote);
         Parametro parametro = new Parametro();
         parametro.setParametros(listaParametros);
              //parametro = null;
         List<Object> ordenFabricacion = (List<Object>)servicioCrud.findNamedQuery("OrdenFab.buscarPor_Lote_tipoSemi", parametro);
         if(ordenFabricacion.size() == 0){
              return null;               
         return ordenFabricacion;
    This method is from an EJB that we use to handle all the DB interaction (DAO)
    @TransactionAttribute(value=TransactionAttributeType.NOT_SUPPORTED)
    public List findNamedQuery(String namedQuery, Parametro parametro) {
         super.setEntityManager(this.entityManager);
         return super.findNamedQuery(namedQuery, parametro);
    In this EJB we are intantiating the entityManager in this way
    @PersistenceContext(unitName="devCrystal~0~entidades~crystal.com.co")
    protected EntityManager entityManager;
    @Resource(name="ORDENES")
    protected javax.sql.DataSource dataSource;
    We are handling the transaction by BEAN.
    This is the parent class for the above EJB.
    @TransactionAttribute(value=TransactionAttributeType.NOT_SUPPORTED)
    public List findNamedQuery(String namedQuery, Parametro parametro) {
         List retorno = null;
         Query query = this.entityManager.createNamedQuery(namedQuery).setFlushMode(FlushModeType.COMMIT);
         setParametros(query, parametro);
         retorno = query.getResultList();
         return retorno;
    protected Query setParametros(Query query, Parametro parametro) {
         if (parametro != null) {
              List<Object> listaParametros = parametro.getParametros();
              if (parametro != null && listaParametros != null) {
                   for (int i = 1; i <= listaParametros.size(); i++) {
                        query.setParameter(i, listaParametros.get(i - 1));
         return query;
    QUERY
    <named-native-query  name="OrdenFab.buscarPor_Lote_tipoSemi" result-class="co.com.crystal.entidades.produccion.OrdenFabricacion">
    <query><![CDATA[ SELECT of.*
    FROM tb_ordenfabricacion of
    WHERE of.co_ordenfabricacion IN
    (SELECT DISTINCT tb_operacionlote.co_ordenfabricacion
    FROM tb_operacionlote
    WHERE tb_operacionlote.fh_terminacion IS NULL AND tb_operacionlote.co_lote = ?)]]>
    </query>
    </named-native-query >
    Entities
    package co.com.crystal.entidades.produccion;
    import java.io.Serializable;
    import java.sql.Timestamp;
    import java.util.List;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;
    import javax.persistence.Transient;
    import javax.persistence.Version;
    @Entity
    @Table(name="TB_ORDENFABRICACION")
    public class OrdenFabricacion implements Serializable {
         @Id
         @Column(name="CO_ORDENFABRICACION")
         private String coOrdenfabricacion;
         @Column(name="FH_ACTUALIZACION")
         @Temporal(TemporalType.TIMESTAMP)     
         private Timestamp fhActualizacion;
         @Column(name="CA_PROGRAMADA")
         private Double caProgramada;
         @Version
         private int version;
         @Column(name="SW_SUMINISTROILIMITADO", nullable = true)
         private String swSuministroilimitado;
         @Column(name="CO_USUARIO")
         private String coUsuario;
         @Column(name="FH_CREACION")
         @Temporal(TemporalType.TIMESTAMP)     
         private Timestamp fhCreacion;
         @Column(name="VL_PORCENTAJEEXCESO", nullable = true)
         private Double vlPorcentajeexceso;
         @ManyToOne     
         @JoinColumn(name="CO_TIPOSEMIELABORADO", nullable = true)
         private TipoSemiElaborado coTiposemielaborado;
         @ManyToOne     
         @JoinColumn(name="CO_CENTRO")
         private Centro coCentro;
         @ManyToOne
         @JoinColumn(name="CO_CATEGORIA", nullable = true)
         private Categoria coCategoria;
         @ManyToOne
         @JoinColumn(name="CO_CLASEORDEN")
         private ClaseOrden coClaseorden;
         @ManyToOne
         @JoinColumn(name="CO_MATERIAL")
         private Material coMaterial;
         @ManyToOne
         @JoinColumn(name="CO_TALLA")
         private Talla coTalla;
         @ManyToOne
         @JoinColumn(name="CO_COLOR")
         private Color coColor;
    /*     //@OneToMany(mappedBy="coOrdenfabricacion", fetch=FetchType.LAZY)
         @Transient
         private List<OperacionLote> tbOperacionLoteCollection;
         @OneToMany(mappedBy="coOrdenfabricacion", fetch=FetchType.LAZY)
         private List<OperacionOrden> tbOperacionordenCollection;
         @OneToMany(mappedBy="coOrdenfabricacion")
         private Set<OrdenPrevFab> tbOrdenprevfabCollection;
         @OneToMany(mappedBy="coOrdenfabricacion")
         private Set<OrdenPrevFab> tbOrdenprevfabCollection;
         private static final long serialVersionUID = 1L;
         public OrdenFabricacion() {
              super();
         public String getCoOrdenfabricacion() {
              return this.coOrdenfabricacion;
         public void setCoOrdenfabricacion(String coOrdenfabricacion) {
              this.coOrdenfabricacion = coOrdenfabricacion;
         public Timestamp getFhActualizacion() {
              return this.fhActualizacion;
         public void setFhActualizacion(Timestamp fhActualizacion) {
              this.fhActualizacion = fhActualizacion;
         public Double getCaProgramada() {
              return this.caProgramada;
         public void setCaProgramada(Double caProgramada) {
              this.caProgramada = caProgramada;
         public Centro getCoCentro() {
              return this.coCentro;
         public void setCoCentro(Centro coCentro) {
              this.coCentro = coCentro;
         public int getVersion() {
              return this.version;
         public void setVersion(int version) {
              this.version = version;
         public String getSwSuministroilimitado() {
              return this.swSuministroilimitado;
         public void setSwSuministroilimitado(String swSuministroilimitado) {
              this.swSuministroilimitado = swSuministroilimitado;
         public String getCoUsuario() {
              return this.coUsuario;
         public void setCoUsuario(String coUsuario) {
              this.coUsuario = coUsuario;
         public TipoSemiElaborado getCoTiposemielaborado() {
              return this.coTiposemielaborado;
         public void setCoTiposemielaborado(TipoSemiElaborado coTiposemielaborado) {
              this.coTiposemielaborado = coTiposemielaborado;
         public Timestamp getFhCreacion() {
              return this.fhCreacion;
         public void setFhCreacion(Timestamp fhCreacion) {
              this.fhCreacion = fhCreacion;
         public Double getVlPorcentajeexceso() {
              return this.vlPorcentajeexceso;
         public void setVlPorcentajeexceso(Double vlPorcentajeexceso) {
              this.vlPorcentajeexceso = vlPorcentajeexceso;
         public Categoria getCoCategoria() {
              return this.coCategoria;
         public void setCoCategoria(Categoria coCategoria) {
              this.coCategoria = coCategoria;
         public ClaseOrden getCoClaseorden() {
              return this.coClaseorden;
         public void setCoClaseorden(ClaseOrden coClaseorden) {
              this.coClaseorden = coClaseorden;
         public Material getCoMaterial() {
              return this.coMaterial;
         public void setCoMaterial(Material coMaterial) {
              this.coMaterial = coMaterial;
         public Talla getCoTalla() {
              return this.coTalla;
         public void setCoTalla(Talla coTalla) {
              this.coTalla = coTalla;
         public Color getCoColor() {
              return this.coColor;
         public void setCoColor(Color coColor) {
              this.coColor = coColor;
         public List<OperacionOrden> getTbOperacionordenCollection() {
              return this.tbOperacionordenCollection;
         public void setTbOperacionordenCollection(List<OperacionOrden> tbOperacionordenCollection) {
              this.tbOperacionordenCollection = tbOperacionordenCollection;
         public Set<Lote> getTbLoteCollection() {
              return tbLoteCollection;
         public void setTbLoteCollection(Set<Lote> tbLoteCollection) {
              this.tbLoteCollection = tbLoteCollection;
         public Set<OrdenPrevFab> getTbOrdenprevfabCollection() {
              return this.tbOrdenprevfabCollection;
         public void setTbOrdenprevfabCollection(Set<OrdenPrevFab> tbOrdenprevfabCollection) {
              this.tbOrdenprevfabCollection = tbOrdenprevfabCollection;
              public Set<TbOrdenprevfab> getTbOrdenprevfabCollection() {
              return this.tbOrdenprevfabCollection;
         public void setTbOrdenprevfabCollection(Set<TbOrdenprevfab> tbOrdenprevfabCollection) {
              this.tbOrdenprevfabCollection = tbOrdenprevfabCollection;
         public List<OperacionLote> getTbLoteCollection() {
              return tbOperacionLoteCollection;
         public void setTbLoteCollection(List<OperacionLote> tbLoteCollection) {
              this.tbOperacionLoteCollection = tbLoteCollection;
    package co.com.crystal.entidades.produccion;
    import java.io.Serializable;
    import java.sql.Timestamp;
    import javax.persistence.Column;
    import javax.persistence.Embeddable;
    import javax.persistence.EmbeddedId;
    import javax.persistence.Entity;
    import javax.persistence.JoinColumn;
    import javax.persistence.JoinColumns;
    import javax.persistence.ManyToOne;
    import javax.persistence.Table;
    import javax.persistence.Temporal;
    import javax.persistence.TemporalType;
    import javax.persistence.Version;
    @Entity
    @Table(name="TB_OPERACIONLOTE")
    public class OperacionLote implements Serializable {
         @EmbeddedId
         private OperacionLote.PK pk;
         @Column(name="CA_PRIMERAS")
         private Integer caPrimeras;
         @Column(name="FH_TERMINACION")
         @Temporal(TemporalType.TIMESTAMP)     
         private Timestamp fhTerminacion;
         @Column(name="FH_INICIO")
         @Temporal(TemporalType.TIMESTAMP)     
         private Timestamp fhInicio;
         @Column(name="FH_ACTUALIZACION")
         @Temporal(TemporalType.TIMESTAMP)     
         private Timestamp fhActualizacion;
         @Column(name="FH_CREACION")
         @Temporal(TemporalType.TIMESTAMP)     
         private Timestamp fhCreacion;
         @Version
         private int version;
         @Column(name="CO_USUARIO")
         private String coUsuario;
         @Column(name="CA_TEORICA")
         private Double caTeorica;
         @Column(name="CA_TEORICAPLC")
         private Double caTeoricaplc;
         @ManyToOne
         @JoinColumn(name="CS_MAQUINA")
         private Maquina csMaquina;
         @Column(name="CO_MAQUINA")
         private String coMaquina;
         @ManyToOne
         @JoinColumns({
              @JoinColumn(name="CO_ORDENFABRICACION", referencedColumnName="CO_ORDENFABRICACION", insertable=false, updatable=false),          
              @JoinColumn(name="CO_LOTE", referencedColumnName="CO_LOTE", insertable=false, updatable=false)
         private Lote tbLote;
         @ManyToOne
         @JoinColumns({
              @JoinColumn(name="CO_ORDENFABRICACION", referencedColumnName="CO_ORDENFABRICACION", insertable=false, updatable=false),          
              @JoinColumn(name="CS_OPERACION", referencedColumnName="CS_OPERACION", insertable=false, updatable=false)
         private OperacionOrden tbOperacionOrden;     
         private static final long serialVersionUID = 1L;
         public OperacionLote() {
              super();
         public OperacionLote.PK getPk() {
              return this.pk;
         public void setPk(OperacionLote.PK pk) {
              this.pk = pk;
         public Integer getCaPrimeras() {
              return this.caPrimeras;
         public void setCaPrimeras(Integer caPrimeras) {
              this.caPrimeras = caPrimeras;
         public Timestamp getFhTerminacion() {
              return this.fhTerminacion;
         public void setFhTerminacion(Timestamp fhTerminacion) {
              this.fhTerminacion = fhTerminacion;
         public Timestamp getFhInicio() {
              return this.fhInicio;
         public void setFhInicio(Timestamp fhInicio) {
              this.fhInicio = fhInicio;
         public Timestamp getFhActualizacion() {
              return this.fhActualizacion;
         public void setFhActualizacion(Timestamp fhActualizacion) {
              this.fhActualizacion = fhActualizacion;
         public Timestamp getFhCreacion() {
              return this.fhCreacion;
         public void setFhCreacion(Timestamp fhCreacion) {
              this.fhCreacion = fhCreacion;
         public int getVersion() {
              return this.version;
         public void setVersion(int version) {
              this.version = version;
         public String getCoUsuario() {
              return this.coUsuario;
         public void setCoUsuario(String coUsuario) {
              this.coUsuario = coUsuario;
         public Double getCaTeorica() {
              return this.caTeorica;
         public void setCaTeorica(Double caTeorica) {
              this.caTeorica = caTeorica;
         public Double getCaTeoricaplc() {
              return this.caTeoricaplc;
         public void setCaTeoricaplc(Double caTeoricaplc) {
              this.caTeoricaplc = caTeoricaplc;
         @Embeddable
         public static class PK implements Serializable {
              @Column(name="CO_ORDENFABRICACION")
              private String coOrdenfabricacion;          
              @Column(name="CO_LOTE")
              private String coLote;
              @Column(name="CS_OPERACION")
              private String csOperacion;
              private static final long serialVersionUID = 1L;
              public PK() {
                   super();
              public String getCoLote() {
                   return this.coLote;
              public void setCoLote(String coLote) {
                   this.coLote = coLote;
              public String getCsOperacion() {
                   return this.csOperacion;
              public void setCsOperacion(String csOperacion) {
                   this.csOperacion = csOperacion;
              public String getCoOrdenfabricacion() {
                   return this.coOrdenfabricacion;
              public void setCoOrdenfabricacion(String coOrdenfabricacion) {
                   this.coOrdenfabricacion = coOrdenfabricacion;
              @Override
              public boolean equals(Object o) {
                   if (o == this) {
                        return true;
                   if ( ! (o instanceof PK)) {
                        return false;
                   PK other = (PK) o;
                   return this.coLote.equals(other.coLote)
                        && this.csOperacion.equals(other.csOperacion)
                        && this.coOrdenfabricacion.equals(other.coOrdenfabricacion);
              @Override
              public int hashCode() {
                   return this.coLote.hashCode()
                        ^ this.csOperacion.hashCode()
                        ^ this.coOrdenfabricacion.hashCode();
         public Lote getTbLote() {
              return tbLote;
         public void setTbLote(Lote tbLote) {
              this.tbLote = tbLote;
         public OperacionOrden getTbOperacionOrden() {
              return tbOperacionOrden;
         public void setTbOperacionOrden(OperacionOrden tbOperacionOrden) {
              this.tbOperacionOrden = tbOperacionOrden;
         public Maquina getCsMaquina() {
              return csMaquina;
         public void setCsMaquina(Maquina csMaquina) {
              this.csMaquina = csMaquina;
         public String getCoMaquina() {
              return coMaquina;
         public void setCoMaquina(String coMaquina) {
              this.coMaquina = coMaquina;
    If you need i can send you also the database traces where you can see the selects and updates over the tables.
    I hope that you can help us with this, we are in a huge problem because of this behavior.
    Best regards,
    Jose Arango.

  • Error in allocating a connection + JPA

    Hello Experts,
    I am trying my first ever JPA Program.I am using netbeans 6.0.In netbeans there is a sample application for WebJPA.In that they are calling entity from servlet.I just made a different project.I have copied all files in my project.At the time of creating persistence unit I have used DB2.But now when I am compiling my project I am getting the following errors.Seems there is some problem with connection to DB2.I have also added the correct jar files during creation of persistence unit.Please help me.Many Thanx in advance.
    *Deploying application in domain failed; Deployment Errorjava.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: Failure in loading T2 native library db2jcct2, reason: java.lang.UnsatisfiedLinkError: no db2jcct2 in java.library.path --*
    Internal Exception: java.sql.SQLException: Error in allocating a connection. Cause: Connection could not be allocated because: Failure in loading T2 native library db2jcct2, reason: java.lang.UnsatisfiedLinkError: no db2jcct2 in java.library.path
    Error Code: 0
    Deployment error:
    The module has not been deployed.
    See the server log for details.
    at org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment.deploy(Deployment.java:163)
    at org.netbeans.modules.j2ee.ant.Deploy.execute(Deploy.java:104)
    at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:288)
    at sun.reflect.GeneratedMethodAccessor1068.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:105)
    at org.apache.tools.ant.Task.perform(Task.java:348)
    at org.apache.tools.ant.Target.execute(Target.java:357)
    at org.apache.tools.ant.Target.performTasks(Target.java:385)
    at org.apache.tools.ant.Project.executeSortedTargets(Project.java:1329)
    at org.apache.tools.ant.Project.executeTarget(Project.java:1298)
    at org.apache.tools.ant.helper.DefaultExecutor.executeTargets(DefaultExecutor.java:41)
    at org.apache.tools.ant.Project.executeTargets(Project.java:1181)
    at org.apache.tools.ant.module.bridge.impl.BridgeImpl.run(BridgeImpl.java:277)
    at org.apache.tools.ant.module.run.TargetExecutor.run(TargetExecutor.java:460)
    at org.netbeans.core.execution.RunClassThread.run(RunClassThread.java:151)
    Caused by: The module has not been deployed.
    at org.netbeans.modules.j2ee.deployment.devmodules.api.Deployment.deploy(Deployment.java:157)

    Hi garava,
    Thanks for the reply.I had followed the same path while creating Persistence Unit.I googled this error & I found a solution where I need to set the NativeLibraryPathPrefix in my JVM.
    For this I went to Servers->Glassfish V2 -> JVM-> .There I set NativeLibraryPathPrefix = D:\Program Files\IBM\SQLLIB\BIN.
    It's working now.But I can't understand what was the problem & how it got solved.
    One more issue ,suppose tom I am facing the same problem for some other XYZ database.Do I need to change this path again for that database.What this path exactly means.I read it looks for "db2jcc2.dll" in this path.What is the need of this dll if I am including jar files during creation of persistence Unit.
    Please help.Thanks in advance.

  • How to check the table existence in JPA

    1) is there a way I can check for existence of the table using JPA, before I read the rows.
    2) If I want to create two tables with same columns (name, time), Should I create two entity objects to insert? is there a way to use one enity class and specify a table to insert ?
    thanks
    Vamshi

    Try this:
    function findNodes(vNode){
         if (vNode.className === "field"){
              if (vNode.isPropertySpecified("name")===true){
                   var myStateName=new RegExp(vNode.name);
                   var returnValue = GFL.search(myStateName);
                   if (returnValue!=-1){
                        this.ui.oneOfChild.border.fill.color.value="192,192,192";
                        this.access="readOnly";
                   else{  
                        this.ui.oneOfChild.border.fill.color.value="255,255,255";//whatever colour is open access
                        this.access="open";
         for (var a=0;a<vNode.nodes.length;a++){
              findNodes(vNode.nodes.item(a));
    findNodes(xfa.form);
    Kyle

  • Unable to deploy Web App using JPA TopLink Essentials in Tomcat5.5.17

    Hi All,
    I am trying to deploy a Web App ( used Top Link Essentials ) to Tomcat and i am getting the following Error..
    I am strating tomcat using -javaagent:/Path/To/spring-agaent.jar
    Dec 14, 2006 9:52:46 AM org.apache.catalina.loader.WebappClassLoader loadClass
    INFO: Illegal access: this web application instance has been stopped already.  Could not load oracle.toplink.essentials.internal.weaving.ClassDetails.  The eventual following stack trace is caused by an error thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access, and has no functional impact.
    java.lang.IllegalStateException
            at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1238)
            at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1198)
            at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
            at oracle.toplink.essentials.internal.weaving.TopLinkWeaver.transform(TopLinkWeaver.java:84)
            at org.springframework.orm.jpa.persistenceunit.ClassFileTransformerAdapter.transform(ClassFileTransformerAdapter.java:56)
            at sun.instrument.TransformerManager.transform(TransformerManager.java:122)
            at sun.instrument.InstrumentationImpl.transform(InstrumentationImpl.java:155)
            at java.lang.ClassLoader.defineClass1(Native Method)
            at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
            at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
            at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:1812)
            at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:866)
            at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1319)
            at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1198)
            at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
            at java.lang.Class.getDeclaredConstructors0(Native Method)
            at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357)
            at java.lang.Class.getConstructor0(Class.java:2671)
            at java.lang.Class.newInstance0(Class.java:321)
            at java.lang.Class.newInstance(Class.java:303)
            at org.apache.myfaces.application.ApplicationImpl.createComponent(ApplicationImpl.java:396)
            at com.sun.faces.config.ConfigureListener.verifyObjects(ConfigureListener.java:1438)
            at com.sun.faces.config.ConfigureListener.contextInitialized(ConfigureListener.java:509)
            at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3729)
            at org.apache.catalina.core.StandardContext.start(StandardContext.java:4187)
            at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:759)
            at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:739)
            at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:524)
            at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:608)
            at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:535)
            at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:470)
            at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1122)
            at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:310)
            at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
            at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1021)
            at org.apache.catalina.core.StandardHost.start(StandardHost.java:718)
            at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1013)
            at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:442)
            at org.apache.catalina.core.StandardService.start(StandardService.java:450)
            at org.apache.catalina.core.StandardServer.start(StandardServer.java:709)
            at org.apache.catalina.startup.Catalina.start(Catalina.java:551)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:585)
            at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:294)
            at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:432) Thanks
    Sateesh

    Spring 2.0 provides custom support for TopLink Essentials in Tomcat out-of-the-box. You should follow the instructions here: http://static.springframework.org/spring/docs/2.0.x/reference/orm.html#orm-jpa-setup-lcemfb-tomcat
    Essentially, Spring provides a custom class loader for Tomcat and doesn't use an agent.
    --Shaun                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to create a cache for JPA Entities using an EJB

    Hello everybody! I have recently got started with JPA 2.0 (I use eclipseLink) and EJB 3.1 and have a problem to figure out how to best implement a cache for my JPA Entities using an EJB.
    In the following I try to describe my problem.. I know it is a bit verbose, but hope somebody will help me.. (I highlighted in bold the core of my problem, in case you want to first decide if you can/want help and in the case spend another couple of minutes to understand the domain)
    I have the following JPA Entities:
    @Entity Genre{
    private String name;
    @OneToMany(mappedBy = "genre", cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Collection<Novel> novels;
    @Entity
    class Novel{
    @ManyToOne(cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Genre genre;
    private String titleUnique;
    @OneToMany(mappedBy="novel", cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Collection<NovelEdition> editions;
    @Entity
    class NovelEdition{
    private String publisherNameUnique;
    private String year;
    @ManyToOne(optional=false, cascade={CascadeType.PERSIST, CascadeType.MERGE})
    private Novel novel;
    @ManyToOne(optional=false, cascade={CascadeType.MERGE, CascadeType.PERSIST})
    private Catalog appearsInCatalog;
    @Entity
    class Catalog{
    private String name;
    @OneToMany(mappedBy = "appearsInCatalog", cascade = {CascadeType.MERGE, CascadeType.PERSIST})
    private Collection<NovelEdition> novelsInCatalog;
    The idea is to have several Novels, belonging each to a specific Genre, for which can exist more than an edition (different publisher, year, etc). For semplicity a NovelEdition can belong to just one Catalog, being such a Catalog represented by such a text file:
    FILE 1:
    Catalog: Name Of Catalog 1
    "Title of Novel 1", "Genre1 name","Publisher1 Name", 2009
    "Title of Novel 2", "Genre1 name","Pulisher2 Name", 2010
    FILE 2:
    Catalog: Name Of Catalog 2
    "Title of Novel 1", "Genre1 name","Publisher2 Name", 2011
    "Title of Novel 2", "Genre1 name","Pulisher1 Name", 2011
    Each entity has associated a Stateless EJB that acts as a DAO, using a Transaction Scoped EntityManager. For example:
    @Stateless
    public class NovelDAO extends AbstractDAO<Novel> {
    @PersistenceContext(unitName = "XXX")
    private EntityManager em;
    protected EntityManager getEntityManager() {
    return em;
    public NovelDAO() {
    super(Novel.class);
    //NovelDAO Specific methods
    I am interested at when the catalog files are parsed and the corresponding entities are built (I usually read a whole batch of Catalogs at a time).
    Being the parsing a String-driven procedure, I don't want to repeat actions like novelDAO.getByName("Title of Novel 1") so I would like to use a centralized cache for mappings of type String-Identifier->Entity object.
    Currently I use +3 Objects+:
    1) The file parser, which does something like:
    final CatalogBuilder catalogBuilder = //JNDI Lookup
    //for each file:
    String catalogName = parseCatalogName(file);
    catalogBuilder.setCatalogName(catalogName);
    //For each novel edition
    String title= parseNovelTitle();
    String genre= parseGenre();
    catalogBuilder.addNovelEdition(title, genre, publisher, year);
    //End foreach
    catalogBuilder.build();
    2) The CatalogBuilder is a Stateful EJB which uses the Cache and gets re-initialized every time a new Catalog file is parsed and gets "removed" after a catalog is persisted.
    @Stateful
    public class CatalogBuilder {
    @PersistenceContext(unitName = "XXX", type = PersistenceContextType.EXTENDED)
    private EntityManager em;
    @EJB
    private Cache cache;
    private Catalog catalog;
    @PostConstruct
    public void initialize() {
    catalog = new Catalog();
    catalog.setNovelsInCatalog(new ArrayList<NovelEdition>());
    public void addNovelEdition(String title, String genreStr, String publisher, String year){
    Genre genre = cache.findGenreCreateIfAbsent(genreStr);//##
    Novel novel = cache.findNovelCreateIfAbsent(title, genre);//##
    NovelEdition novEd = new NovelEdition();
    novEd.setNovel(novel);
    //novEd.set publisher year catalog
    catalog.getNovelsInCatalog().add();
    public void setCatalogName(String name) {
    catalog.setName(name);
    @Remove
    public void build(){
    em.merge(catalog);
    3) Finally, the problematic bean: Cache. For CatalogBuilder I used an EXTENDED persistence context (which I need as the Parser executes several succesive transactions) together with a Stateful EJB; but in this case I am not really sure what I need. In fact, the cache:
    Should stay in memory until the parser is finished with its job, but not longer (should not be a singleton) as the parsing is just a very particular activity which happens rarely.
    Should keep all of the entities in context, and should return managed entities form mehtods marked with ##, otherwise the attempt to persist the catalog should fail (duplicated INSERTs)..
    Should use the same persistence context as the CatalogBuilder.
    What I have now is :
    @Stateful
    public class Cache {
    @PersistenceContext(unitName = "XXX", type = PersistenceContextType.EXTENDED)
    private EntityManager em;
    @EJB
    private sessionbean.GenreDAO genreDAO;
    //DAOs for other cached entities
    Map<String, Genre> genreName2Object=new TreeMap<String, Genre>();
    @PostConstruct
    public void initialize(){
    for (Genre g: genreDAO.findAll()) {
    genreName2Object.put(g.getName(), em.merge(g));
    public Genre findGenreCreateIfAbsent(String genreName){
    if (genreName2Object.containsKey(genreName){
    return genreName2Object.get(genreName);
    Genre g = new Genre();
    g.setName();
    g.setNovels(new ArrayList<Novel>());
    genreDAO.persist(t);
    genreName2Object.put(t.getIdentifier(), em.merge(t));
    return t;
    But honestly I couldn't find a solution which satisfies these 3 points at the same time. For example, using another stateful bean with an extended persistence context (PC) would work for the 1st parsed file, but I have no idea what should happen from the 2nd file on.. Indeed, for the 1st file the PC will be created and propagated from CatalogBuilder to Cache, which will then use the same PC. But after build() returns, the PC of CatalogBuilder should (I guess) be removed and re-created during the succesive parsing, although the PC of Cache should stay "alive": shouldn't in this case an exception being thrown? Another problem is what to do when the Cache bean is passivated. Currently I get the exception:
    "passivateEJB(), Exception caught ->
    java.io.IOException: java.io.IOException
    at com.sun.ejb.base.io.IOUtils.serializeObject(IOUtils.java:101)
    at com.sun.ejb.containers.util.cache.LruSessionCache.saveStateToStore(LruSessionCache.java:501)"
    Hence, I have no Idea how to implement my cache.. Can you please tell me how would you solve the problem?
    Many thanks!
    Bye

    Hi Chris,
    thanks for your reply!
    I've tried to add the following into persistence.xml (although I've read that eclipseLink uses L2 cache by default..):
    <shared-cache-mode>ALL</shared-cache-mode>
    Then I replaced the Cache bean with a stateless bean which has methods like
    Genre findGenreCreateIfAbsent(String genreName){
    Genre genre = genreDAO.findByName(genreName);
    if (genre!=null){
    return genre;
    genre = //Build new genre object
    genreDAO.persist(genre);
    return genre;
    As far as I undestood, the shared cache should automatically store the genre and avoid querying the DB multiple times for the same genre, but unfortunately this is not the case: if I use a FINE logging level, I see really a lot of SELECT queries, which I didn't see with my "home made" Cache...
    I am really confused.. :(
    Thanks again for helping + bye

  • How to create Insert & Update on master-detail form JPA/EJB 3.0

    Is there any demonstration or tips how to Insert record on master-details form for JPA/EJB 3.0 with ADF binding?

    I have master-detail forms (dept-emp). I drag the dept->operations->create method to JSF page. But when I click create button, only dept form is clear and ready for insert. But emp form is not clear. How can I add create method for this?
    Can you give some example how to pass the right object to the persist or merge method so that it can save both the two objects (master-detail tables)
    Thanks
    Edited by: user560557 on Oct 9, 2009 8:58 AM

  • How to use Oracle partitioning with JPA @OneToOne reference?

    Hi!
    A little bit late in the project we have realized that we need to use Oracle partitioning both for performance and admin of the data. (Partitioning by range (month) and after a year we will move the oldest month of data to an archive db)
    We have an object model with an main/root entity "Trans" with @OneToMany and @OneToOne relationships.
    How do we use Oracle partitioning on the @OneToOne relationships?
    (We'd rather not change the model as we already have millions of rows in the db.)
    On the main entity "Trans" we use: partition by range (month) on a date column.
    And on all @OneToMany we use: partition by reference (as they have a primary-foreign key relationship).
    But for the @OneToOne key for the referenced object, the key is placed in the main/source object as the example below:
    @Entity
    public class Employee {
    @Id
    @Column(name="EMP_ID")
    private long id;
    @OneToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="ADDRESS_ID")
    private Address address;
    EMPLOYEE (table)
    EMP_ID FIRSTNAME LASTNAME SALARY ADDRESS_ID
    1 Bob Way 50000 6
    2 Sarah Smith 60000 7
    ADDRESS (table)
    ADDRESS_ID STREET CITY PROVINCE COUNTRY P_CODE
    6 17 Bank St Ottawa ON Canada K2H7Z5
    7 22 Main St Toronto ON Canada     L5H2D5
    From the Oracle documentation: "Reference partitioning allows the partitioning of two tables related to one another by referential constraints. The partitioning key is resolved through an existing parent-child relationship, enforced by enabled and active primary key and foreign key constraints."
    How can we use "partition by reference" on @OneToOne relationsships or are there other solutions?
    Thanks for any advice.
    /Mats

    Crospost! How to use Oracle partitioning with JPA @OneToOne reference?

  • One to one relationship in jpa

    I have two relation table like , I would Like to try select by UID by JPA ,
    select *from student as P, Address as A where P.UserId=A.UserId
    and A.UpdateId=uid;
    step one
    I have my persistence.xml testing by single table
    step two I have two entity class from DB
    in my student{} @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Basic(optional = false)
    @Column(name = "UserId", nullable = false)
    private Integer userId;.....
    in my address I have
    @JoinColumn(name = "UserId", referencedColumnName = "UserId", nullable = false)
    @OneToOne(cascade=CascadeType.ALL, mappedBy="Student")
    private Student student;
    what else I need to do in order to let it work??

    jsutherl wrote:
    To do a join in JPA you can either use "join" or the "." notation for a OneToOne.
    i.e.
    Select s from Student s where s.address.updateId = :id
    You would need a OneToOne from Student to Address for this.
    @OneToOne(mappedBy="student")
    private Address address;
    James : http://www.eclipselink.org
    I guest I get the part that you post , but if I want to display the information out of two tables, but in Servlet
    Query query=em.createNamedQuery("?");
    List stList=query.getResultList();
    Iterator stIterator=stList.iterator();
    while(stIterator.hasNext()){
    *? which class?*=?.stIterator.next();} ??
    Thank you!

Maybe you are looking for

  • Is my Creative Suite 1.1.1 compatible with windows 8.1?

    I am a retired pastor who has used InDesign to create my sermon outlines for years. I now need to update my computer and will have to use Windows 8.1. Will my old CS 1.1.1 (from 1984) work with Windows 8.1. I cannot possible afford to go to a new ver

  • Infix vs Touch Up Tool

    Just an FYI, for any of you who are struggling with the Text Touch Up Tool when the text is oddly linked between different blocks, give Infix a try.  Infix is an excellent PDF editor that my company uses at times for pdf reporting needs.  Monthly, it

  • Retrieving mailing  lists by connecting to LDAP(windows AD)

    Hi All, I have crunch requirement, for retrieving mailing lists and the members in the list fromwindows ad(ldap) .The mailing group location and mailing group name are the serach parameters. Required help on the same. (a code sample is appreciated) T

  • I can't open Numbers anymore

    It gives me an error message with the text: The Numbers app can't be opened -1712. What am I supposed to do to get it to work again??

  • Mac OSX pre-installed?

    Just received my new macbook (Core 2 Duo - 2.0 Ghz - 80 gig) for which I did not need to use the install disks as when I turned it on it asked me all my personal details, .mac memebership and then I directly hit the desktop. This is different from wh