4

I am lost on how to use composite keys with annotations and hibernate...

So for instance I have this table that has:

TABLE_A

INIT, NUM, CNT, TYP

TABLE_B

INIT, NUM, V_CNT

TABLE A and B primary keys are composite keys consisting of INIT and NUM

I want to run my query:

   "FROM TABLE_A AS A " +
   "LEFT JOIN A.hiber_join AS B " +
   "WHERE A.INIT||A.NUM IN (:carList) AND A.INIT IN (:initList) AND A.NUM IN              (:numberList) " + 
    "AND B.V_CNT > 0

My Classes look like:

*Class_A*

public class TABLE_A implements Serializable{

private String INIT;
private String NUM;
private Integer CNT;
private String TYP;

    @OneToOne
@JoinTable(name = "TABLE_B",
    joinColumns = {@JoinColumn(name = "INIT"), @JoinColumn(name = "NUM")}

)
protected TABLE_B hiber_join;

    public TABLE_A()
    {}

    public void doHibernateStuff()
    {
     //call query get result set
    }

}

//Class B

public class TABLE_B implements Serializable{

private String NUM;
private String INIT;
private Integer V_CNT;
}

I tried to make it as simple as possible because I need to from the very basics of how to use hibernate and the annotations...as you can tell I have a been working a while and hibernate documentation and other questions has not seemed to help...

JonH
  • 501
  • 7
  • 13
  • 25

1 Answers1

1

AFAIK, you need to use PrimaryKeyJoinColumn (I changed the class and attribute names to conform to standard Java naming conventions, but you should choose meaningful names):

public class BEntity implements Serializable{

    @Id
    @Column(name = "NUM")
    private String num;

    @Id
    @Column(name = "INIT")
    private String init;

    @Column(name = "V_CNT")
    private Integer vcnt;
}

public class AEntity implements Serializable{

    @Id
    @Column(name = "NUM")
    private String num;

    @Id
    @Column(name = "INIT")
    private String init;

    @OneToOne
    @PrimaryKeyJoinColumns({
        @PrimaryKeyJoinColumn(name="NUM", referencedColumnName="NUM"),
        @PrimaryKeyJoinColumn(name="INIT", referencedColumnName="INIT")
    })
    private BEntity bEntity;
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • What if my `AEntity` class doesn't have `init` variable then how this `@OneToOne` will be done ? Pls help me in this case – ngCoder Dec 19 '16 at 14:06