Created
April 18, 2015 19:41
-
-
Save jkneal/154e9897e8afcd5f36d8 to your computer and use it in GitHub Desktop.
Training - JPA Converter
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 train; | |
import java.awt.Color; | |
import javax.persistence.AttributeConverter; | |
import javax.persistence.Converter; | |
@Converter | |
public class ColorConverter implements AttributeConverter { | |
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])); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment