Last active
November 4, 2019 16:08
-
-
Save thjanssen/d778d226c455659fd867 to your computer and use it in GitHub Desktop.
JPA 2.1 - How to implement an Attribute Converter (http://www.thoughts-on-java.org/2013/10/jpa-21-how-to-implement-type-converter.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
package blog.thoughts.on.java.jpa21.converter; | |
import java.awt.Color; | |
import javax.persistence.AttributeConverter; | |
import javax.persistence.Converter; | |
@Converter | |
public class ColorConverter implements AttributeConverter<Color, String> { | |
private static final String SEPARATOR = "\\|"; | |
/** | |
* Convert Color object to a String | |
* with format red|green|blue|alpha | |
*/ | |
@Override | |
public String convertToDatabaseColumn(Color color) { | |
StringBuilder sb = new StringBuilder(); | |
sb.append(color.getRed()).append(SEPARATOR) | |
.append(color.getGreen()) | |
.append(SEPARATOR) | |
.append(color.getBlue()) | |
.append(SEPARATOR) | |
.append(color.getAlpha()); | |
return sb.toString(); | |
} | |
/** | |
* Convert a String with format red|green|blue|alpha | |
* to a Color object | |
*/ | |
@Override | |
public Color convertToEntityAttribute(String colorString) { | |
String[] rgb = colorString.split(SEPARATOR); | |
return new Color(Integer.parseInt(rgb[0]), | |
Integer.parseInt(rgb[1]), | |
Integer.parseInt(rgb[2]), | |
Integer.parseInt(rgb[3])); | |
} | |
} |
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 RectangleEntity | |
{ | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Integer id; | |
@Column | |
private Integer x; | |
@Column | |
private Integer y; | |
@Column | |
@Convert(converter = ColorConverter.class) | |
private Color color; | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment