I'm struggling with a problem that seems way too easy:
Setup is two Entities with a Many-To-One Relationsship in Hibernate 3:
@Entity
class M {
private N n;
@ManyToOne(fetch = FetchType.LAZY)
public N getN() { return n; }
public void setN(N n) { this.n = n; }
}
@Entity
class N {
private List<M> ms = new ArrayList<M>();
@OneToMany(mappedBy="n")
public List<M> getMs() { return ms; }
public void setMs(List<M> ms) { this.ms = ms; }
}
Easy enough. In my application, I have a list of M
s that either have an N
or don't. This list is the input for a h:dataTable
that shows different column content depending on whether the FK is null or not. But when I test m.getN() != null
this causes hibernate to load N
. How can I avoid this?
Edit: this is actually an error of mine, as pointed out by JBNizet in the comments. To at least make this useful to someone and keep with the layout above, I've rephrased the question to "How do I get the foreign key column value of a dependent Hibernate Entity without fetching the full entity?" as suggested by Aaron Digulla.
Edit 2: Turns out the new question is a duplicate of this one: How can I prevent Hibernate fetching joined entities when I access only the foreign key id? - so, close vote?
mappedBy tells Hibernate how to create instances of your entities and load the data into them. It should refer to the field name in the class that you are annotating, PersonDetail in this instance, where the relationship is defined.
mappedBy attribute In JPA or Hibernate, entity associations are directional, either unidirectional or bidirectional. Always mappedBy attribute is used in bidirectional association to link with other side of entity. In the above tables, BRANCH and STUDENT tables has One-To-Many association.
The @JoinColumn annotation helps us specify the column we'll use for joining an entity association or element collection. On the other hand, the mappedBy attribute is used to define the referencing side (non-owning side) of the relationship.
Annotation Type JoinColumn. Specifies a column for joining an entity association or element collection. If the JoinColumn annotation itself is defaulted, a single join column is assumed and the default values apply. (Optional) The SQL fragment that is used when generating the DDL for the column.
Create a projection mapping which contains M or several fields of M and e.g. id of N
Your query might liook sopething like
select new com.my.ProjectionObject(m, m.n.id) from M m where ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With