[英]Ordering in many-to-many relation (Java Spring)
There is 2 models with relation many-to-many: 有2个与多对多关系的模型:
@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: 将
List
而不是Set
与@OrderColumn
批注结合使用:
https://docs.oracle.com/javaee/6/api/javax/persistence/OrderColumn.html 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. 这将在
route_points
创建一个附加列,以跟踪元素的顺序,包括插入,删除和重新排序。
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. 请注意,JPA会将顺序保持为连续数字,因此对列表进行的大多数(如果不是全部)结构修改将导致每个元素的更新声明。
Set
basicly does not hold order of insertion. Set
基本上不保留插入顺序。 LinkedHashSet
however will keep order of insertion of elements you could try that. 但是,
LinkedHashSet
将保持插入元素的顺序,您可以尝试这样做。 It will store Point
into database in proper order, but most probably it again will be mixed up after fetching from the database. 它将以适当的顺序将
Point
存储到数据库中,但是很可能在从数据库中获取后再次将其混合。 You have to viable options here: 您必须在此处提供可行的选择:
Set
use List
insteed. Set
use List
insteed。 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 Set
并将private Integer index
字段添加到Point
并存储适当的索引-提取后就可以对其进行排序而没有任何问题 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 如果确保将点以正确的顺序保留在数据库中,则可以假设您使用的是唯一,无间隔,自动生成的PK序列,则可以省略其他列并按
id
排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.