Skip to content

Instantly share code, notes, and snippets.

@banterCZ
Last active June 21, 2020 09:40
Show Gist options
  • Save banterCZ/6164973 to your computer and use it in GitHub Desktop.
Save banterCZ/6164973 to your computer and use it in GitHub Desktop.
JPA abstract entity - better way
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import java.io.Serializable;
@MappedSuperclass
public abstract class AbstractEntity<PK extends Serializable> {
public static final String GENERATOR = "customSequence";
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = GENERATOR)
private PK id;
public PK getId() {
return id;
}
public void setId(PK id) {
this.id = id;
}
@Override
public int hashCode() {
if (getId() != null) {
return getId().hashCode();
}
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
AbstractEntity<?> other = (AbstractEntity<?>) obj;
if (getId() == null || other.getId() == null) {
return false;
}
if (!getId().equals(other.getId())) {
return false;
}
return true;
}
}
import javax.persistence.*;
@Entity
@SequenceGenerator(name = AbstractEntity.GENERATOR, sequenceName="SQ_USERS")
@AttributeOverride(name="id", column=@Column(name = "USER_ID"))
public class User extends AbstractEntity<Long> {
@Column(name = "USR_NAME", nullable = false)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@b0c1
Copy link

b0c1 commented Oct 9, 2019

And how do you implement another entity with a different sequence name?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment