简体   繁体   中英

How to implement Composite Primary key and Composite Foreign Key using JPA,Hibernate, Springboot

I searched a lot for this particular problem but i didn''t find any specific solution. I have a Composite Primary Key in one table and one of the field from this composite primary key is the part of the Composite Primary Key of another table. You can say that this particular field is the foreign key in the second table but ia not defining any exclusive Foreign Key constraint in the table definition. There can be multiple Records in the second table for each rec in the first table.i am trying to implement this using SPringBoot-JPA-Hibernate but not being able to do so. Can some body help me here. Here are the detais:-

I have a USER_CREDENTIAL table with following fields:-

CREATE TABLE `INSTITUTION_USER_CREDENTIAL` (
    `INSTITUTION_USER_ID INT(10) NOT NULL,  -> AutoGeneratd
    `INSTITUTION_USER_NAME` VARCHAR(50) NOT NULL,
    `INSTITUTION_USER_PASSWORD` VARCHAR(50) NOT NULL,
    `FIRST_NAME` VARCHAR(100) NOT NULL,
    `MIDDLE_NAME` VARCHAR(100),
    `LAST_NAME` VARCHAR(100) NOT NULL,
    PRIMARY KEY (`INSTITUTION_USER_ID`,`INSTITUTION_USER_NAME`) 
   );

2) Here is my second table

CREATE TABLE `INSTITUTION_USER_CREDENTIAL_MASTER` (
`INSTITUTION_ID` INT(10) NOT NULL,  -> Autogenerated
`INSTITUTION_USER_ID`  INT(10) NOT NULL, -> Coming from 
                                           INSTITUTION_USER_CREDENTIAL
`INSTITUTION_USER_ROLE`  CHAR(02) NOT NULL, 
`INSTITUTION_USER_STATUS` CHAR(02) NOT NULL,
`INSTITUTION_NAME` VARCHAR(200) NOT NULL,
`LAST_UPDT_ID` VARCHAR(100) NOT NULL,
`LAST_UPDT_TS` DATETIME NOT NULL,
PRIMARY KEY(`INSTITUTION_ID`,`INSTITUTION_USER_ID`,`INSTITUTION_USER_ROLE`)
);

Note that i haven't declare any particular foreign key in the second table. I have two @Embeddable Class corresponding to two primary key structure for two different table:-

For the INSTITUTION_USER_CREDENTIAL table:-

@Embeddable
public class InstitutionUserCredentialPrimaryKey implements Serializable{

private static final long serialVersionUID = 1L;

@Column(name = "INSTITUTION_USER_ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private int institutionUserId;

@Column(name = "INSTITUTION_USER_NAME")
private String institutionUserName;
//Getter-Setters removed for clarity
}

Corresponding Entity Class:-

@Entity(name = "INSTITUTION_USER_CREDENTIAL")
public class InstitutionUserCredential {

@EmbeddedId
private InstitutionUserCredentialPrimaryKey 
        institutionUserCredentialPrimaryKey;

@Column(name = "INSTITUTION_USER_PASSWORD")
private String instituteUserPassword;

@Column(name = "FIRST_NAME")
private String firstname;

@Column(name = "MIDDLE_NAME")
private String middleName;

@Column(name = "LAST_NAME")
private String lastName;

@OneToMany(mappedBy="institutionUserCredential", cascade = CascadeType.ALL)
private List<InstitutionUserCredentialMaster> 
           institutionUserCredentialMaster;
//Getter-Setter and other part of the code removed for clarity
}

For the INSTITUTION_USER_CREDENTIAL_MASTER table:-

@Embeddable
public class InstituteUserCredentialMasterPrimaryKey implements Serializable 
{

private static final long serialVersionUID = 1L;

@Column(name = "INSTITUTION_ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private int institutionId;

@Column(name = "INSTITUTION_USER_ID")
private int institutionUserId;

@Column(name = "INSTITUTION_USER_ROLE")
private String userRole;

//Getter-Setter and other part of the code removed for clarity
}

Entity Class:-

@Entity(name = "INSTITUTION_USER_CREDENTIAL_MASTER")
 public class InstitutionUserCredentialMaster {

@EmbeddedId
private InstituteUserCredentialMasterPrimaryKey 
   instituteUserCredentialMasterPrimaryKey;

@Column(name = "INSTITUTION_USER_STATUS")
private String userStatus;

@Column(name = "INSTITUTION_NAME")
private String institutionName;

@Column(name = "LAST_UPDT_ID")
private String lastUpdateId;

@Column(name = "LAST_UPDT_TS")
private String lastUpdateTimestamp;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumns({
    @JoinColumn(name="institutionUserId", referencedColumnName = 
              "INSTITUTION_USER_ID")
})
private InstitutionUserCredential institutionUserCredential;

//Getter-Setter and other part of the code removed for clarity
}

Note that only 1 field INSTITUTION_USER_ID, is getting used in the Composite PrimaryKey of the InstitutionUserCredentialMaster and is coming from the composite primary key of the InstitutionUserCredential.

When i am running my code this is giving me an error like :-

Invocation of init method failed; nested exception is 
org.hibernate.AnnotationException: 
referencedColumnNames(INSTITUTION_USER_ID) of com.bnl.application.entity.InstitutionUserCredentialMaster.institutionUserCredential referencing com.bnl.application.entity.InstitutionUserCredential not mapped to a single property

None of the examples i have seen so far involving the Composite Primary key and foreign key doesn't treat any one particular field and is more of the entire key structure. I am using MYSQL and i have checked that we can create table having composite primary key and one of the field from that composite key is foreign key in another table and also part of the Composite Primary key of the second table.

Any pointers appreciated

UPDATE:- In my first post i made a mistake while posting it. I am sorry that institutionUserName became a part of the InstitutionUserCredentialMaster . it was a typo. There is no existence of the intitutionUserName in the InstitutionUserCredentialMaster table. i have fixed that and updated the post.

***** Update based on the input by Niver and Wega *****

Update to the InstitutionUserCredentialMasterPrimaryKey

@Embeddable

public class InstituteUserCredentialMasterPrimaryKey implements Serializable {

private static final long serialVersionUID = 1L;

@Column(name = "INSTITUTION_ID")
@GeneratedValue(strategy=GenerationType.AUTO)
private int institutionId;

@Column(name = "INSTITUTION_USER_ID")
private int institutionUserId;
// Added the institutionUserName
@Column(name = "INSTITUTION_USER_NAME")
private String institutionUserName;

@Column(name = "INSTITUTION_USER_ROLE")
private String userRole;
}

Update to the Entity Class InsstitutionUserCredentialMaster :-

@Entity(name = "INSTITUTION_USER_CREDENTIAL_MASTER")

public class InstitutionUserCredentialMaster {

@EmbeddedId
private InstituteUserCredentialMasterPrimaryKey instituteUserCredentialMasterPrimaryKey;

@Column(name = "INSTITUTION_USER_STATUS")
private String userStatus;

@Column(name = "INSTITUTION_NAME")
private String institutionName;

@Column(name = "LAST_UPDT_ID")
private String lastUpdateId;

@Column(name = "LAST_UPDT_TS")
private String lastUpdateTimestamp;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumns({
    @JoinColumn(name="institutionUserId", referencedColumnName = "INSTITUTION_USER_ID"),
    @JoinColumn(name="institutionUserName",referencedColumnName = "INSTITUTION_USER_NAME")
})
private InstitutionUserCredential institutionUserCredential;
}

This time i am getting an error like

Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: Table [institution_user_credential_master] contains physical column name [institution_user_id] referred to by multiple physical column names: [institutionUserId], [INSTITUTION_USER_ID]

I think that the problem is that you are not referencing the other part of the EmbeddedId in the JoinColumns annotation. You have defined that also the institutionUserName is part of the primary key, so you should mention it as well in the definition of the foreign key in entity InstitutionUserCredentialMaster .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM