Last active
June 21, 2020 09:40
-
-
Save banterCZ/6164973 to your computer and use it in GitHub Desktop.
JPA abstract entity - better way
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
And how do you implement another entity with a different sequence name?