Mahmoud Saleh
Mahmoud Saleh

Reputation: 33625

How to define foreign key only in an entity without primary key

hi my tables are as follows:

1- medical_company:

2- account_entity:

ENTITIES:

1- MedicalCompany:

@SuppressWarnings("serial")
@Entity
@Table(name = "medical_company")
public class MedicalCompany implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "medical_company_id", unique = true, nullable = false)
@Basic(fetch = FetchType.EAGER)
private Long id;

}

2- AccountEntity:

@SuppressWarnings("serial")
@Entity
@Table(name = "account_entity")
public class AccountEntity implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "account_entity_id", unique = true, nullable = false)
    @Basic(fetch = FetchType.EAGER)
    private Long id;

}

i want to make medical_company_id in medical_company table as foreign key without defining a primary key, how to accomplish that ?

Upvotes: 0

Views: 3017

Answers (2)

Ramesh Kotha
Ramesh Kotha

Reputation: 8322

Hibernate wont allow to define entity with out PK. So you should declare medical_company_id as a primary key and make it foreign key for account_entity table.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 692121

Entities must have an ID. That's mandatory. Whether this ID is an actual PK in database or not is not important (although I don't see any reason not to define it as a PK), but the ID must be immutable and unique across all rows of the table.

Upvotes: 1

Related Questions