Rishi
Rishi

Reputation: 3

Entity mapping using a non primary key column

I am using hibernate and Mysql in the java project for persistence. I have two entities Transaction and Service. Transaction is having many to one relation to service. I wanted to use a non primary column(SERVICE_CODE) of type VARCHAR from Service table as a foreign key in the Transaction table. But when I do so I get the following exception.

SQL Error: 1452, SQLState: 23000
Cannot add or update a child row: a foreign key constraint fails.

SERVICE_CODE is defined as non null and unique in database. Following example works fine if I use primary key from Service table for mapping.

@Entity
@Table(name="Transaction")
public class Transaction {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="TRANSACTION_ID")
    long transactionId;


    @ManyToOne
    @JoinColumn(name="SERVICE_CODE")
    Service service;
}


@Entity
@Table(name="SERVICE")
public class Service {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="SERVICE_ID")
    Long serviceId;

    @Column(name="SERVICE_CODE")
    String serviceCode; 
}

Upvotes: 0

Views: 3786

Answers (1)

Bohuslav Burghardt
Bohuslav Burghardt

Reputation: 34796

As explained in this article, you should use the referencedColumnName attribute of the @JoinColumn annotation to specify the referenced column of the foreign key relationship.

@ManyToOne
@JoinColumn(name="SERVICE_CODE", referencedColumnName="SERVICE_CODE")
Service service;

With this modification the DDL is generated correctly like this:

alter table Transaction
    add constraint FK_5k37nrtsvi22y2jhsde903ps9
    foreign key (SERVICE_CODE)
    references SERVICE (SERVICE_CODE);

and with your original code like this (it references primary key of the SERVICE table instead of the SERVICE_CODE column):

alter table Transaction
    add constraint FK_5k37nrtsvi22y2jhsde903ps9
    foreign key (SERVICE_CODE)
    references SERVICE;

Upvotes: 1

Related Questions