据我所知,DB需要一个compareTo方法才能理解这些是同一个对象,所以我为下面的对象写了一个与methd的比较
@JsonIgnoreProperties(ignoreUnknown = true)
@Entity
@Table(name = "networkServiceConfig")
public class NetworkServiceConfig implements Serializable{
String endpoint;
String url;
String host;
int port;
String networkServiceName;
String uuid;
@JsonIgnore
@OneToOne(mappedBy="networkServiceConfig")
Service service;
private static final long serialVersionUID = 1L;
@JsonProperty
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
long id;
public NetworkServiceConfig() {
}
public NetworkServiceConfig(String endpoint, String url, String host, int port, String networkServiceName) {
this.endpoint = endpoint;
this.url = url;
this.host = host;
this.port = port;
this.networkServiceName = networkServiceName;
}
public String getEndpoint() {
return this.endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
public void setNetworkServiceName(String name) {
this.networkServiceName = name;
}
public String getNetworkServiceName() {
return this.networkServiceName;
}
public String getUuid() {
return this.uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
/**
* Implement comparable to compare two NetworkServiceConfig objects for equality
*/
public int compareTo(NetworkServiceConfig o) {
if (o == null) {
return 1;
}
if (this.networkServiceName.equals(o.networkServiceName)) {
return 0;
}
int value = (int) (this.id - o.id);
if (value == 0) {
return this.networkServiceName.compareTo(o.networkServiceName);
}
return value;
}
@Override
public boolean equals(Object obj) {
NetworkServiceConfig o = (NetworkServiceConfig) obj;
return this.networkServiceName.equals(o.networkServiceName);
}
}
网络服务名称对于每个对象都是唯一的。但是每次我将这个对象保存到各种保存调用时,我都会看到20行。请注意,因此我们在不同对象上的属性 这是关系
服务对象:
@OneToOne (cascade= CascadeType.ALL)
@JoinColumn(name="networkServiceConfig_id")
@JsonProperty
NetworkServiceConfig networkServiceConfig;
此外,我没有在表中看到networkServiceConfig_id列
答案 0 :(得分:0)
我认为您有点困惑,与Java相比较或类似的实现,在您使用Collections Framework时用于排序对象,但它与Hibernate或JPA的数据库实现没有直接关系
答案 1 :(得分:0)
最好的方法是在保存和更新networkServiceConfig
之前检查networkServiceName
表NetworkServiceConfig
重复项,如果networkServiceName
已存在则返回422 HTTP状态。这样检查更新有点棘手。
除了你应该在数据库级别添加保护,正如@ xiaofeng.li建议的那样。您可以为networkServiceName
添加唯一约束,或将该字段作为主键。
如果您使用NetworkServiceConfig
作为参考表,则应删除cascade= CascadeType.ALL
。此外,如果多个@ManyToOne
可以拥有相同的Service
NetworkServiceConfig
并从Service
移除NetworkServiceConfig
关联
@ManyToOne
@JoinColumn(name="networkServiceConfig_id")
@JsonProperty
NetworkServiceConfig networkServiceConfig;