I had a strange problem with requests to select n + 1. My mapping is as follows:
@Entity
@IdClass(MyTablePK.class)
@Table(name = "my_table", schema = "schema")
public class MyTable {
@Id
@Column(name = "name", nullable = false, length = 12)
private String name="";
@Id
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "myStringValue", referencedColumnName = "myStringValue")
private AdditionalData data;
... (other fields, getters, setters)
}
public class MyTablePK implements Serializable {
private String name;
private AdditionalData data;
(getters,setters)
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyTablePK that = (MyTablePK) o;
if (name!= null ? !name.equals(that.name) : that.name!= null) return false;
return !(data!= null ? !data.equals(that.data) : that.data!= null);
}
@Override
public int hashCode() {
int result = name!= null ? name.hashCode() : 0;
result = 31 * result + (data!= null ? data.hashCode() : 0);
return result;
}
}
@Entity
@Table(name = "info", schema = "schema")
public class AdditionalData implements Serializable {
@Id
@Column(name = "recno")
private Long recno;
@Column(name = "info1", length = 3)
private String info1;
@Column(name = "info2", length = 3)
private String info2;
... (getters, setters)
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
AdditionalData data = (AdditionalData) o;
return recno.equals(data.recno);
}
@Override
public int hashCode() {
return recno.hashCode();
}
}
Now I select all the values from MyTable. As expected, I get n + 1 selects, for each row of MyTable a new AdditionalData request comes in. To combat this, I wrote a request to select a connection:
FROM MyTable mytab join fetch mytab.data
Which, however ... has not changed anything.
Now it’s interesting that if I ignore business requirements for a moment and delete @IdClass, making name@Id the only one - everything works correctly, all data is received with one request. Why is this? Can't I fight n + 1 with the composite id part?
In case this is relevant - I am using Hibernate 4.3.5.Final with an Oracle database