简体   繁体   中英

Ordering in many-to-many relation (Java Spring)

There is 2 models with relation many-to-many:

@Entity
public class Map {
  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @JsonIgnore
  private long mapId;

  @NotBlank
  private String title;

  @ManyToMany(cascade = CascadeType.ALL)
  @JoinTable(name = "route_points",
             joinColumns = @JoinColumn(name = "mapId", referencedColumnName = "mapId"),
             inverseJoinColumns = @JoinColumn(name = "pointId", referencedColumnName = "pointId"))
  private Set<Point> points;
}

@Entity
public class Point {
  @Id
  private String pointId;
  @NotBlank
  private String city;
  @ManyToMany(mappedBy = "points")
  private Set<Map> maps;
}

I have to save an order of points in the set and record it to the intermediate table. How it can be done? Thx.

Use a List instead of a Set in combination with the @OrderColumn annotation:

https://docs.oracle.com/javaee/6/api/javax/persistence/OrderColumn.html

This will create an additional column in route_points to track the order of elements, including insertion, deletion, and reordering.

Please note that JPA will maintain the ordering as consecutive numbers, so most (if not all) structural modifications to the list will result in an update statement for each and every element.

Set basicly does not hold order of insertion. LinkedHashSet however will keep order of insertion of elements you could try that. It will store Point into database in proper order, but most probably it again will be mixed up after fetching from the database. You have to viable options here:

  1. Dont use Set use List insteed.
  2. Stick with Set and add private Integer index field to Point and store proper indexes - you will be able to sort that after fetch without any problems

If you ensure that points will be persisted in right order into databse, then you could ommit additional column and sort by id assuming you are using unique, no gaps, autogenerated sequence for PKs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM