SQL JPA – Multiple columns as primary key

We Are Going To Discuss About SQL JPA – Multiple columns as primary key. So lets Start this Java Article.

SQL JPA – Multiple columns as primary key

  1. SQL JPA – Multiple columns as primary key

    If all fields in the class are part of primary key, then solution would be pretty simple (extending solution provided by @raul-cuth):
    @Entity @IdClass(EntityExample.class) public class EntityExample implements Serializable {

  2. SQL JPA – Multiple columns as primary key

    If all fields in the class are part of primary key, then solution would be pretty simple (extending solution provided by @raul-cuth):
    @Entity @IdClass(EntityExample.class) public class EntityExample implements Serializable {

Solution 1

You need to have a class for your composite key:

public class CompositeKey implements Serializable {
    private int column1;
    private int column2;
    private int column3;
}

and then in your entity class use the @IdClass annotation:

@Entity
@IdClass(CompositeKey.class)
public class EntityExample {
    @Id
    private int column1;
    @Id
    private int column2;
    @Id
    private int column3;
    ...
    ...
}

I think this should work. Hope it helps, cheers!

Yea and there is the other solution, the one that @jklee mentioned, both work, it’s a matter of preference.

Original Author Raul Cuth Of This Content

Solution 2

Use @Embeddable and @EmbeddedId.

Example:

@Entity
public class Project implements Serializable {
    @EmbeddedId ProjectId id;
}
 
@Embeddable
class ProjectId implements Serializable {
    int departmentId;
    long projectId;
}

More information here http://www.objectdb.com/java/jpa/entity/id#Embedded_Primary_Key_

Original Author jklee Of This Content

Solution 3

If all fields in the class are part of primary key, then solution would be pretty simple (extending solution provided by @raul-cuth):

@Entity
@IdClass(EntityExample.class)
public class EntityExample implements Serializable {

    @Id
    private int column1;

    @Id
    private int column2;

    @Id
    private int column3;
}

Original Author heroin Of This Content

Solution 4

  1. Using @IdClass annotation on the @Entity class followed by @Id annotation on individual fields that are part of composite primary key.
  2. Alternatively can make use of @Embeddable class which can consist of individual fields of the composite primary key and then a reference of this class can be used as an attribute with @Embedded annotation in @Entity class.
    Hope this helps.

Original Author Penguin Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment