views:

41

answers:

2

I have to tables I want to map to each other. I want to populate 2 drop down lists: code_r and code_l. When i choose a value from code_r, code_l should display only certain records. In my database I have 2 tables:

Table code_r
===================
CODE         INT
LIBELLE      VARCHAR

And

Table code_l
===================
ID           BIGINT
CODE_R_ID    INT
LIBELLE      VARCHAR

One code_r can have multiple code_l associated with it (based on the code_r_id (not a defined as a Foreign key in the code_l definition). Of course, a code_l can only be associated to one code_r.

The following SQL query works fine:

SELECT * 
FROM code_r r
 left join `code_l` l on l.code_r_id = r.code;

How should I implement that using using JPA/Hibernate-3.5 annotations in the CodeR and CodeL classes??

Any help would be appreciated. Thanks in advance.

+2  A: 

in the CodeR class:

@OneToMany(mappedBy="code_r_id")

Collection elementsFromL;


in the CodeL class:

@ManyToOne

CodeR code_r_id;

Mr Q.C.
Thank you for your answer Mr Q.C :-)
kiwifrog
+2  A: 

With Hibernate (and now standardized in JPA 2.0), you can use a unidirectional one-to-many association without a join table using a JoinColumn annotation:

Annotate the CodeR like this:

@Entity
public class CodeR {
   @Id
   private Integer code;
   private String libelle;

   @OneToMany
   @JoinColumn(name="CODE_R_ID")
   Set<CodeL> codeLs = new HashSet<CodeL>():

   // getters, setters
}   

And CodeL

@Entity
public class CodeL {
   @Id
   private Integer id;
   private String libelle;

   // getters, setters, equals, hashCode
}   

And the JPQL query:

SELECT r FROM CodeR LEFT JOIN  r.codeLs
Pascal Thivent
@Pascal Thivent +1 for standardized JPA 2.0 @JoinColumn without @JoinTable
Arthur Ronald F D Garcia
@Pascal Thivent And congratulations for earning golden badge on Hibernate
Arthur Ronald F D Garcia
@Arthur Thank you very much, sincerely appreciated. Next target, JPA :)
Pascal Thivent
Thanks a lot Pascal, it managed to get the list of codeL for each codeR. But unfortunately, when I try to get a list of codeR, each codeR is duplicated for each codeL it is associated with (left join instead of inner join?). How could I fix this?? Thanks in advance?
kiwifrog