Created
July 19, 2018 21:06
-
-
Save j-dimension/9a2a02352fffaa4de59b03d26ed67c66 to your computer and use it in GitHub Desktop.
Automatic database index creation using JPA (https://www.j-dimension.com/automatic-database-index-creation-with-the-java-persistence-api/)
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
package com.jdimension.jpaindextest; | |
import java.io.Serializable; | |
import javax.persistence.Entity; | |
import javax.persistence.GeneratedValue; | |
import javax.persistence.GenerationType; | |
import javax.persistence.Id; | |
import javax.persistence.Index; | |
import javax.persistence.NamedQueries; | |
import javax.persistence.NamedQuery; | |
import javax.persistence.Table; | |
/** | |
* JPA entity class with automatic index creation | |
* @author j-dimension | |
*/ | |
@Entity | |
@Table(name = "JpaIndex", | |
indexes = {@Index(name = "idx_id", columnList="id", unique = true), | |
@Index(name = "idx_somevalue", columnList="someValue", unique = false)}) | |
@NamedQueries({ | |
@NamedQuery(name = "JpaIndex.findAll", query = "SELECT a FROM JpaIndex a"), | |
@NamedQuery(name = "JpaIndex.findBySomeValue", query = "SELECT a FROM JpaIndex a WHERE a.someValue = :someValue")}) | |
public class JpaIndex implements Serializable { | |
private static final long serialVersionUID = 1L; | |
@Id | |
@GeneratedValue(strategy = GenerationType.AUTO) | |
private Long id; | |
private String someValue; | |
public Long getId() { | |
return id; | |
} | |
public void setId(Long id) { | |
this.id = id; | |
} | |
@Override | |
public int hashCode() { | |
int hash = 0; | |
hash += (id != null ? id.hashCode() : 0); | |
return hash; | |
} | |
@Override | |
public boolean equals(Object object) { | |
// TODO: Warning - this method won't work in the case the id fields are not set | |
if (!(object instanceof JpaIndex)) { | |
return false; | |
} | |
JpaIndex other = (JpaIndex) object; | |
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { | |
return false; | |
} | |
return true; | |
} | |
@Override | |
public String toString() { | |
return "com.jdimension.jpaindextest.JpaIndex[ id=" + id + " ]"; | |
} | |
/** | |
* @return the someValue | |
*/ | |
public String getSomeValue() { | |
return someValue; | |
} | |
/** | |
* @param someValue the someValue to set | |
*/ | |
public void setSomeValue(String someValue) { | |
this.someValue = someValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also see my blog post for this topic: https://www.j-dimension.com/automatic-database-index-creation-with-the-java-persistence-api/