HQL Hibernate un-related entities, but same id

272 views Asked by At

I have 2 classes

  • Verification
  • Contract

with the following structure:

  public class Verification implements Serializable {
     private Long verificationId;
     private Long salesManCode;
     private Long clientCode;
     ...
  }

  public class Contract implements Serializable {
     private Long contractId;
     private Long salesManCode;
     private Long clientCode;
     ...
  }

These classes have their respectives hbm.xml maps, in the database model the tables do not have association, neither in the hibernate mapping, but when saving a Contract, it must have the same verificationId y the contractId field (Business Rules), but some cases are also given contracts without verification.

verification
 verificationId | salesManCode | clientCode
  1050              1001            2056
  1051              1001            2248
  1054              1002            2856

contract
 contractId | salesManCode |clientCode
  1050         1001          2056         <- this contract have verification
  1051         1001          2248         <- this contract have verification
  1052         1025          2822         <- this contract not have verification
  1053         1254          1547         <- this contract not have verification
  1054         1002          2856         <- this contract have verification

My problem is when I run the HQL query:

select con.salesManCode,  ver.salesManCode, con.clientCode, ver.clientCode, con.contracId, ver.verificationId 
from Verification ver, Contract con
where ver.verificationId = con.contractId

but Hibernate translate with a cross join sentence and combine all records. Is there any method to execute a HQL query between un-related classes in hbm.xml files?

RULE: should not be mapped entities.

1

There are 1 answers

0
Vlad Mihalcea On BEST ANSWER

You can map the join relationship between the two tables as follows:

@Entity
public class Verification implements Serializable {
    private Long verificationId;

    private Long salesManCode;
    private Long clientCode;
    ...
}

@Entity
public class Contract implements Serializable {
    private Long contractId;        

    @MapsId
    @OneToOne
    @JoinColumn(name = "contractId", referencedColumnName = "verificationId")
    private Verification verification;

    private Long salesManCode;
    private Long clientCode;
}

The your query becomes:

select con.salesManCode, ver.salesManCode, con.clientCode, ver.clientCode, con.contracId, ver.verificationId 
from Contract con
join con.verification ver

So instead of a CROSS JOIN you get an INNER JOIN.