Created
April 19, 2015 03:13
-
-
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)
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
public List findTripsByVehicle(Vehicle vehicle) { | |
Query query = this.em.createNamedQuery("Trip.findByVehicle"); | |
query.setParameter("vehicle", vehicle); | |
return query.getResultList(); | |
} |
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
@NamedQueries(@NamedQuery(name = "Trip.findByVehicle", query = "SELECT trip FROM Trip trip WHERE vehicle=:vehicle")) |
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
@Entity | |
public class Trip { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Integer id; | |
private Vehicle vehicle; | |
... | |
} |
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
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."); | |
} | |
} |
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
@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