projectlombok/lombok

[FEATURE] Generate JPA boilerplate code for composite identifiers with @IdClass.

Open

#2032 opened on Jan 25, 2019

View on GitHub
 (10 comments) (0 reactions) (0 assignees)Java (12,535 stars) (2,310 forks)batch import
enhancementhelp wantedlow-priority

Description

Describe the feature

Annotation to generate JPA boilerplate code for composite identifiers with @IdClass.

As stated here:

  • The composite identifier must be represented by a "primary key class". The primary key class may be defined using the javax.persistence.IdClass annotation.
  • The primary key class must be public and must have a public no-arg constructor.
  • The primary key class must be serializable.
  • The primary key class must define equals and hashCode methods.

Example:

@Entity
@IdClassAnnotation
public class SystemUser {
	@Id
	private String subsystem;
	
	@Id
	private String username;
}

Will generate:

@Entity
@IdClass(SystemUser.PK.class)
public class SystemUser {
	@Id
	private String subsystem;

	@Id
	private String username;

	public PK getId() {
		return new PK(subsystem, username);
	}

	public void setId(PK id) {
		this.subsystem = id.getSubsystem();
		this.username = id.getUsername();
	}

	public static class PK implements Serializable {
		private static final long serialVersionUID = 1L;

		private String subsystem;
		private String username;

		public PK() {
		}

		public PK(String subsystem, String username) {
			this.subsystem = subsystem;
			this.username = username;
		}

		public String getSubsystem() {
			return subsystem;
		}

		public void setSubsystem(String subsystem) {
			this.subsystem = subsystem;
		}

		public String getUsername() {
			return username;
		}

		public void setUsername(String username) {
			this.username = username;
		}

		@Override
		public int hashCode() {
			final int prime = 31;
			int result = 1;
			result = prime * result + ((subsystem == null) ? 0 : subsystem.hashCode());
			result = prime * result + ((username == null) ? 0 : username.hashCode());
			return result;
		}

		@Override
		public boolean equals(Object o) {
			if (o == this)
				return true;
			if (!(o instanceof PK))
				return false;
			PK other = (PK) o;
			if (!other.canEqual((Object) this))
				return false;
			if (!super.equals(o))
				return false;
			if (this.subsystem != other.subsystem)
				return false;
			if (this.username != other.username)
				return false;
			return true;
		}

		protected boolean canEqual(Object other) {
			return other instanceof PK;
		}
	}
}

Describe the target audience Developers using the java persistence api, for instance spring developers using spring data jpa

Additional context

  1. I though this was not generic enough to be in this project but then I read this discussion and looks like this could go in the lombok.extern.jpa package

Contributor guide