, .
, @PreUpdate, @PrePersists, @PostUpdate , , . , , , .
@Convert, jpa 2.1 (@UserType ). jpa , / .
@Convert anotation, AttributeConverter.
public class Parent {
@Id
private Integer id;
@Convert(converter = FriendConverter.class)
private Set<Parent>friends;
}
:
@Component
public class FriendConverter implements AttributeConverter<List, String>{
@Autowired
private SomeRepository someRepository;
@Override
public String convertToDatabaseColumn(List attribute) {
StringBuilder sb = new StringBuilder();
for (Object object : attribute) {
Parent parent = (parent) object;
sb.append(parent.getId()).append(".");
}
return sb.toString();
}
@Override
public List convertToEntityAttribute(String dbData) {
String[] split = dbData.split(".");
List<Parent>friends = new ArrayList<>();
for (String string : split) {
Parent parent = someRepository.findById(Integer.valueOf(string));
friends.add(accion);
}
return friends;
}
}
, .
As a personal comment, I recommend matching the relationship as it should. In the future, this will allow you to avoid problems. AttributeConverter comes in handy when working with enums
source
share