Danh Ngoc Phi
Danh Ngoc Phi

Reputation: 45

Hibernate Annotation, how to use @Joincolumn refer to a foreign key?

I use Hibernate 3.6.8. Here is my tables:

CREATE TABLE UTILIZATION (
ID BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY 
... 
FK_WORKCATEGORY SMALLINT,
CONSTRAINT PK_UTILIZATION PRIMARY KEY ( ID));

CREATE TABLE DB2ADMIN.WORKCATEGORY(
ID SMALLINT NOT NULL,
DESCRIPTION VARCHAR(50),
CONSTRAINT PK_WORKCATEGORY PRIMARY KEY(ID));

ALTER TABLE UTILIZATION ADD FOREIGN KEY (FK_WORKCATEGORY) REFERENCES WORKCATEGORY(ID); 

my Pojos:

@Entity
@Proxy(proxyClass=IWorkCategory.class)
@Table(name="WORKCATEGORY")
public class WorkCategory extends BoBase implements Serializable, IWorkCategory{

    @Id
    private Integer Id;
    private String description;

    @Override
    public Serializable getId() {
        return Id;
    }
    @Override
    public void setId(Serializable id) {
        Id = (Integer)id;
    }
    @Override
    public String getDescription() {
        return description;
    }
    @Override
    public void setDescription(String description) {
        this.description = description;
    }   
} 

@Entity
@Proxy(proxyClass=IUtilization.class)
@Table(name="UTILIZATION")
public class Utilization extends BoBase implements Serializable, IUtilization{

    @Id     
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long Id;    

    private WorkCategory workCategory;


    @ManyToOne(fetch=FetchType.LAZY, targetEntity=WorkCategory.class)
    @JoinColumn(name="FK_WORKCATEGORY", updatable=false, insertable=false)
    public WorkCategory getWorkCategory() {
        return workCategory;
    }


    public void setWorkCategory(WorkCategory workCategory) {
        this.workCategory = workCategory;
    }
}

As you can see the table Utilization refer to table WorkCategory by foreign key FK_WORKCATEGORY, but in Utilization pojo, i declare this property with the name workCategory. When I run unit test for Utilization bo = UtilizationDAO.get(new Long(123)), the SQL is generated with the column UTILIZATIO0_.WORKCATEGORY, instead of FK_WORKCATEGORY. I have put the @JoinColumn(name="FK_WORKCATEGORY", in the Utilization Pojo, but it doesn't help. Please help me to fix this error. Thanks in advance.

Upvotes: 1

Views: 18781

Answers (1)

JB Nizet
JB Nizet

Reputation: 692281

That's because you put your annotation on the getter rather than putting in on the field. Since the @Id annotation is put on a field, Hibernate expects all the annotations to be on fields.

Upvotes: 5

Related Questions