JPAã®ãã¼ã¸ã§ã³ã¯2.1ã¨åãã¼ã¸ã§ã³ãã0.1ããä¸ãã£ã¦ããªãããé常ã«ãããã®ã追å ããã¦ããã
2.1ã®ç®çæ©è½ã¨ãã¦ã¯ã¹ãã¢ãå¼ã³åºããå¯è½ã«ãªã£ãã¨ãããã®ã ããããåºæ¬ã¹ãã¢ã使ããããªãã®ã§ãããã¯ç¡è¦ããã
ã§ãå°å³ã»ã»ã»ã§ã¯ãªããæ´¾æãªã®ã«ãã¾ãèªãããªãæ°æ©è½ãããã
ãããã³ã³ãã¼ã¿ã ããã£ã¨ããï¼
ããã¯ã©ããããã®ãã¨ããã¨ããã¨ãã°ãDBä¸ã«ã¯æååã§ä¿åããã¦ãEntityä¸ã¯Integerã§ä¿æããã¨ãã£ããã®ã
ãã¡ãããã©ããã¯ã©ã¹ä»¥å¤ã§ããµã¤ãã«ä½¿ããã®ã§ãã¢ããªã±ã¼ã·ã§ã³ã«åããã¦ç©æ¥µçã«ã³ã³ãã¼ã¿ãä½ã£ã¦ããã¨æ¢åã®DBãå¤æ´ããããã¨ãã£ã¦ããã«Entityæä½ãå¼ãããããªããé常ã«è¯ããã®ãåºæ¥ä¸ããã
ã³ã¼ãã¯æ¨æ¥ã®ã¨ã³ããªã®JPA2.0ã®ãµã³ãã«ããã¨ã«å¤æ´ãã¦ã¿ããã
addressã¨ããæåååã«ã¯é½éåºçãå
¥ã£ã¦ããã®ã§ãããã«ä½¿ã£ã¦ã¿ãã
ãããDBä¸ã¯æååã®ã¾ã¾å¤æ´ãããEntityä¸ã§æ±ãå ´åã¯Integerã§é½éåºçã³ã¼ããå©ç¨ããããã«ãã¦ã¿ããã
ã³ã³ãã¼ã¿ä½æ
@Converter public class AddressConverter implements AttributeConverter<Integer, String>{ @Override public String convertToDatabaseColumn(Integer x) { if(x == null){ return ""; } switch(x){ case 1:return "åæµ·é"; case 2:return "é森ç"; case 3:return "岩æç"; case 4:return "å®®åç"; case 5:return "ç§ç°ç"; case 6:return "山形ç"; case 7:return "ç¦å³¶ç"; default:return "ãã¨ã¯ããã©ãã"; } } @Override public Integer convertToEntityAttribute(String y) { if(y == null){ return null; } switch(y){ case "åæµ·é":return 1; case "é森ç":return 2; case "岩æç":return 3; case "å®®åç":return 4; case "ç§ç°ç":return 5; case "山形ç":return 6; case "ç¦å³¶ç":return 7; default:return -1; } } }
Entityã«ã³ã³ãã¼ã¿ãè¨å®ãã
@Entity @Access(AccessType.FIELD) public class Customer implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) public Long id; public String name; @Convert(converter = AddressConverter.class) public Integer address; }
ã@Convertãããããããã§ã³ã³ãã¼ã¿ã®ã¯ã©ã¹ãè¨å®ããã
ã°ãã¼ãã«è¨å®
ã°ãã¼ãã«ã«è¨å®ããå ´åã¯ã³ã³ãã¼ã¿ã®æå®ã¯ãããªããªããè¨å®æ¹æ³ã¯ç°¡åã
@Converter(autoApply = true)
ããã ãã§ãã®åãè¦ã¤ããã¨èªåã§ã³ã³ãã¼ã¿ãé©ç¨ãããã
ãã®ãããä¸è¨ã®ãµã³ãã«ã®ãããªIntegerã¨ãã©ããã¯ã©ã¹ã§ã¯å©ç¨ãã¦ã¯ãããªãã
Integerã使ã£ã¦ããã¨ãããã¹ã¦ã«é©ç¨ããã¦ãã¾ãããã ã
ã³ã³ãã¼ã¿ã®ããããããããã ããããããã§ãªãã¸ã§ã¯ãæåãããã³ã¼ããæ¨æºAPIã®ã¿ã§æ¸ããã
ã³ã¬ã¯ã·ã§ã³çãªãã®ãå®å
¨ã«ã«ã³ãåºåãã§æååã¨ãã¦çªã£è¾¼ããåãåºãã¨ããå¯è½ã ã
JavaSEã§åããå ´åãã³ã³ãã¼ã¿ã®ã¯ã©ã¹ãJPAã«èªåç»é²ãããªãããEntityã¨åããpersistence.xmlã¾ãã¯orm.xmlã«è¨è¿°ããã¨ããã ããã