Java – hibernate manytoone n 1 select id

N 1 select query I encountered a strange problem My mapping looks like this:

@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 values from mytable As expected, I get n 1 choices and a new additionaldata query arrives for each mytable row In order to win, I wrote a connection acquisition query:

FROM MyTable mytab join fetch mytab.data

But... Nothing has changed

Now, interestingly, if I temporarily ignore the business requirements and delete @ IdClass to make the name unique @ ID - everything is normal, and all data is obtained through a single query Why? Can't I use a part of the composite ID against the N 1 selection?

If it is relevant – I use hibernate 4.3 5. Final and Oracle Database

Solution

This may be related to known issues here: https://hibernate.atlassian.net/browse/HHH-10292

Try mapping the mystringvalue column twice Once it is part of the ID and string, it is used as additionaldata again, where insertable = false and updatable = false in the join column

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>