Search code examples
javadatabasejpapersistencejpql

EntityManager.find behavior with an object containing 2 id as primary key


I'm starting to step into the Java world and I'm having troubles to understand this.

I'm using JPA to interact with my database with JPQL.

I have a persistent class like this one :

@Entity
@Table(name="C_A_T")
@NamedQuery(name="CAT.findAll", query="SELECT c FROM CAT c")
public class CAT implements Serializable {
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    private CATPK id;
    private String offer;
    @Temporal(TemporalType.DATE)
    @Column(name="MODIF_DATE")
    private Date modifDate;


    public CAT() {}
    public CATPK getId() {return id;}
    public void setId(CATPK id) {this.id = id;}
    public String getOffer() {return offer;}
    public void setOffer(String offer) {this.offer = offer;} 
    public Date getModifDate() {return modifDate;}
    public void setModifDate(Date modifDate) {this.modifDate= modifDate;}
    /* ... */
}

The class CATPK represents a primary key of an instance of CAT :

@Embeddable
public class CATPKimplements Serializable {
    //default serial version id, required for serializable classes.
    private static final long serialVersionUID = 1L;
    @Column(name="ID_CAT")
    private String idCAT;
    @Column(name="ID_DEMANDE")
    private String idDemande;

    public CATPK() {}
    public String getIdCAT() {return this.idCAT;}
    public void setIdCAT(String idCAT) {this.idCat= idCat;}
    public String getIdDemande() {return this.idDemande;}
    public void setIdDemande(String idDemande) {this.idDemande = idDemande;}
    /* ...*/
}

So basicly, the primay key is made of 2 different ID.

Now, sometimes, before inserting a CAT in my database I checked if it is not already in the C_A_T table :

EntityManagerFactory emf = Persistence.createEntityManagerFactory("cie");
em = emf.createEntityManager();
em.getTransaction().begin();
// inCAT is an instance of CAT on which there is a complete primary key CATPK (made of 2 id)
CAT CATinDB = em.find( CAT.class, inCAT.getId() );
if (null == CATinDB)
  em.persist(inCAT); // CAT created
em.getTransaction().commit();
em.close();

Now, the problem is that the line em.find( CAT.class, inCAT.getId() ); doesn't return null when it should.

For instance, CATinDB can contain a row when I actually have no rows with the right idCAT and idDemande.

So will find consider that it is found with only one id of the catPK matching ?

In the end, I changed the line :

if (null == CATinDB)

into :

if (null == CATinDB || CATinDB.getId().getIdCAT() != inCAT.getId().getIdCAT() || CATinDB.getId().getIdDemande() != inCAT.getId().getIdDemande())

Not really sure why find wasn't returning null when I had no records matching the 2 id.


Solution

  • Actually, I just needed to restart my weblogic server. Looks like the data source is not dynamically updated when I update the database.