I have two tables with foreign key references:
Comm TABLE:
+----+------------+
| ID | NAME |
+----+------------+
| 1 | comm name1 |
| 2 | comm name2 |
| 3 | comm name3 |
+----+------------+
LOCATION TABLE: - COMM_ID FK to Comm --> id
+---------+------+-----+
| COMM_ID | FORM | TO |
+---------+------+-----+
| 1 | 720 | 721 |
| 1 | 725 | |
| 1 | | 766 |
| 1 | | |
| 2 | 766 | 225 |
| 3 | 766 | 222 |
+---------+------+-----+
The problem is Hibernate returns my comm object
with missing location in SET<location>
All rows where there is no FROM and TO (like the last row with COMM_ID = 1 in table LOCATION) are missing.
Otherwise (if only one of FROM or TO) the row is returned...
why?
Comm objects:
@ElementCollection
@CollectionTable(name="LOCATION",joinColumns=@JoinColumn(name="COMM_ID"))
public Set<LOCATION> getLocations(){
return locations;
}
public void setLocations(Set<LOCATION> locations){
this.locations=locations;
}
Location class:
@Embeddable
class Location implements java.io.Serializable {
private BigDecimal fromLocationId;
private BigDecimal toLocationId;
public Location() {
}
public Location(BigDecimal fromLocationId, BigDecimal toLocationId) {
this.fromLocationId = fromLocationId;
this.toLocationId = toLocationId;
}
@Column(name="FROM", nullable=true, precision=22, scale=0)
public BigDecimal getFromLocationId() {
return this.fromLocationId;
}
public void setFromLocationId(BigDecimal fromLocationId) {
this.fromLocationId = fromLocationId;
}
@Column(name="TO", nullable=true, precision=22, scale=0)
public BigDecimal getToLocationId() {
return this.toLocationId;
}
public void setToLocationId(BigDecimal toLocationId) {
this.toLocationId = toLocationId;
}
@Override
public int hashCode() {
return com.google.common.base.Objects.hashCode(fromLocationId, toLocationId);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
final LOCATION other = (LOCATION) obj;
return com.google.common.base.Objects.equal(this.fromLocationId, other.fromLocationId) && com.google.common.base.Objects.equal(this.toLocationId, other.toLocationId);
}
}
I'm using Hibernate - 4.3.6
LOG:
org.hibernate.SQL -
select
locations0_.COMM_ID as COMM_ID1_2_0_,
locations0_.FROM as FROM2_8_0_,
locations0_.TO as TO4_8_0_
from
LOCATION locations0_
where
locations0_.COMM_ID=1
I checked it in my DB and it's return the correct result.
LOCATIONclass. Since you're usingSetit is mandatory that you override theequalsandhashCodemethod correctly.public boolean equals(com.google.common.base.Object obj)This doesn't look right. Please post the full class. And check if you post the real code.com.google.common.base.Objects.equal(this.fromLocationId, other.fromLocationId)is dangerous here. Since it should callBigDecimal#equalsand this implementation is very restrictive about "equal" instances. To check if this is the problem, please test this implementation or useListinstead ofSet