Skip to content

Instantly share code, notes, and snippets.

@thjanssen
Created April 19, 2015 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thjanssen/f075ef7f281e203dcf3b to your computer and use it in GitHub Desktop.
Save thjanssen/f075ef7f281e203dcf3b to your computer and use it in GitHub Desktop.
JPA 2.1 Attribute Converter - The better way to persist enums (http://www.thoughts-on-java.org/2013/10/jpa-21-type-converter-better-way-to.html)
public List findTripsByVehicle(Vehicle vehicle) {
Query query = this.em.createNamedQuery("Trip.findByVehicle");
query.setParameter("vehicle", vehicle);
return query.getResultList();
}
@NamedQueries(@NamedQuery(name = "Trip.findByVehicle", query = "SELECT trip FROM Trip trip WHERE vehicle=:vehicle"))
@Entity
public class Trip {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Vehicle vehicle;
...
}
public enum Vehicle {
CAR("C"), BUS("B"), TRAIN("T"), PLANE("P");
private String shortName;
Vehicle(String shortName) {
this.shortName = shortName;
}
public String getShortName() {
return this.shortName;
}
public static Vehicle fromShortName(String shortName) {
for (Vehicle v : Vehicle.values()) {
if (v.getShortName().equals(shortName)) {
return v;
}
}
throw new IllegalArgumentException("No Vehicle with shortName ["
+ shortName + "] found.");
}
}
@Converter(autoApply = true)
public class VehicleConverter implements AttributeConverter {
@Override
public String convertToDatabaseColumn(Vehicle vehicle) {
return vehicle.getShortName();
}
@Override
public Vehicle convertToEntityAttribute(String shortName) {
return Vehicle.fromShortName(shortName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment