문서의 선택한 두 판 사이의 차이를 보여줍니다.
다음 판 양쪽 다음 판 | |||
java:jpa:converter [2018/07/11 14:39] kwon37xi 만듦 |
java:jpa:converter [2018/07/11 14:43] kwon37xi |
||
---|---|---|---|
줄 4: | 줄 4: | ||
* [[http:// | * [[http:// | ||
+ | <code java> | ||
+ | @Converter | ||
+ | public class PersonNameConverter implements | ||
+ | AttributeConverter< | ||
+ | |||
+ | private static final String SEPARATOR = ", "; | ||
+ | |||
+ | @Override | ||
+ | public String convertToDatabaseColumn(PersonName personName) { | ||
+ | if (personName == null) { | ||
+ | return null; | ||
+ | } | ||
+ | |||
+ | StringBuilder sb = new StringBuilder(); | ||
+ | if (personName.getSurname() != null && !personName.getSurname() | ||
+ | .isEmpty()) { | ||
+ | sb.append(personName.getSurname()); | ||
+ | sb.append(SEPARATOR); | ||
+ | } | ||
+ | |||
+ | if (personName.getName() != null | ||
+ | && !personName.getName().isEmpty()) { | ||
+ | sb.append(personName.getName()); | ||
+ | } | ||
+ | |||
+ | return sb.toString(); | ||
+ | } | ||
+ | |||
+ | @Override | ||
+ | public PersonName convertToEntityAttribute(String dbPersonName) { | ||
+ | if (dbPersonName == null || dbPersonName.isEmpty()) { | ||
+ | return null; | ||
+ | } | ||
+ | |||
+ | String[] pieces = dbPersonName.split(SEPARATOR); | ||
+ | |||
+ | if (pieces == null || pieces.length == 0) { | ||
+ | return null; | ||
+ | } | ||
+ | |||
+ | PersonName personName = new PersonName(); | ||
+ | String firstPiece = !pieces[0].isEmpty() ? pieces[0] : null; | ||
+ | if (dbPersonName.contains(SEPARATOR)) { | ||
+ | personName.setSurname(firstPiece); | ||
+ | |||
+ | if (pieces.length >= 2 && pieces[1] != null | ||
+ | && !pieces[1].isEmpty()) { | ||
+ | personName.setName(pieces[1]); | ||
+ | } | ||
+ | } else { | ||
+ | personName.setName(firstPiece); | ||
+ | } | ||
+ | |||
+ | return personName; | ||
+ | } | ||
+ | } | ||
+ | @Entity(name = " | ||
+ | public class Person { | ||
+ | |||
+ | @Convert(converter = PersonNameConverter.class) | ||
+ | private PersonName personName; | ||
+ | |||
+ | // ... | ||
+ | } | ||
+ | </ |