Display homing fields in JPA

Suppose we have a class of user entities. The user can be friends with other users. How can I map this self-promotion collection field without creating a new object called “Connection” or creating multiple records in the database?

@Entity
public class User {
...
@ManyToMany
private Collection<User> friends;
...
}

USER_ID-FRIEND_ID
1 - 2
2 - 1 (duplicate... I don't need it)
+5
source share
4 answers

You cannot - you need both entries in the database.

Actually, for relations with friendship, I would say that a graph base such as neo4j is the right thing to use. There you have two users and just add “friends”.

+1
source

Below is a snapshot of my code for ElementEntity:

@OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private List<ElementEntity> children;

@JoinColumn(name = "ParentId", referencedColumnName = "ElementId")
@ManyToOne(fetch = FetchType.LAZY)
private ElementEntity parent;

:

  • ElementId - ;
  • ParentId
+6

, relational table.

, USER FRIENDS:

user_id friend_id
   1      2

@Bozho , (neo4j).

+1

, .

, @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

0
source

All Articles