Reputation: 81
I have an @Entity
with three fields A, B, C out of which A and B act as composite primary key. I created an @EmbeddedId
class holding A and B. To ease the burden of defining getters and setters i used lombok @Data
annotation.
@Entity
@Data
public class MyClass {
@EmbeddedId
private PrimaryKey id;
}
@Embeddable
@Data
public class PrimareyKey implements Serializable {
private String A;
private String B;
}
I would not like to expose that A and B are the primary key and access A and access all fields in the same way.
//Exposes primary key
myObject.getid().getA();
myObject.getid().getB();
myObject.getC();
//Hides primary key
myObject.getA();
myObject.getB();
myObject.getC();
Currently one could use @IdClass
tagging each filed as @Id
as suggested in this answer but if I still need to use @EmbeddedId
(or any @Embedded
actually) the only way (I know) to achieve this is to write ad hoc getters and setters bypassing the id variable such as
@Entity
@Data
public class MyClass {
@EmbeddedId
private PrimaryKey id;
public String A getA(){
return id.getA()
}
public String A setA(String a){
id.setA(a);
}
//same for B and any other fiels in PrimaryKey
}
This looks like a lot of boilerplate code to write and maintain.
Is there an annotation to expose @EmbeddedId
getters and setters?
Upvotes: 4
Views: 3528
Reputation: 13855
You can use the AccessLevel with @Getter and @Setter as follows:
@Getter(AccessLevel.NONE)
@Setter(AccessLevel.NONE)
private PrimaryKey id;
When using @Data, you have the public access to accessors by default, and using AccessLevel.NONE will overwrite the default behaviour and will not allow to access the accessors.
Upvotes: 1
Reputation: 761
In MyClass, add Lombok @Delegate
annotation to your PrimaryKey. It should look like:
@Entity
@Data
public class MyClass {
@Delegate
@EmbeddedId
private PrimaryKey id;
}
Then you can set/get PrimaryKey fields directly from MyClass. Here is a link for you to read more about it.
Upvotes: 3