【发布时间】:2017-03-15 15:09:51
【问题描述】:
我有一些实体类具有一对多 - 多对一的关系。我正在使用 Spring 和 Hibernate。
每个TwoWayService 在我的应用程序中恰好有2 个Services。
摘录:
@Entity
@Table(name = "two_way_services")
public class TwoWayService {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column
private String name;
@OneToMany(cascade = CascadeType.ALL,
mappedBy = "twoWayService",
fetch = FetchType.EAGER)
private List<Service> services;
public TwoWayService() {
services = new ArrayList<>();
// Add two as default
services.addAll(Arrays.asList(new Service(), new Service()));
}
public void setService1(Service service) {
services.set(0, service);
service.setTwoWayService(this);
}
public void setService2(Service service) {
services.set(1, service);
service.setTwoWayService(this);
}
...
}
@Entity
@Table(name = "services")
public class Service {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column
private String name;
@ManyToOne(optional = false)
@JoinColumn
private TwoWayService twoWayService;
public void setTwoWayService(TwoWayService twoWayService) {
this.twoWayService = twoWayService;
}
...
}
我在后端使用 Derby。数据库架构是这样的:
CREATE TABLE two_way_services (
id INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
config_name VARCHAR(255) NOT NULL,
name VARCHAR(80),
admin_ip VARCHAR(32) NOT NULL,
connection_state INT NOT NULL
);
CREATE TABLE services (
id INT NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1),
name VARCHAR(80),
type INT NOT NULL,
ruleset VARCHAR(255) NOT NULL,
two_way_service_id INT,
FOREIGN KEY (two_way_service_id) REFERENCES two_way_services(id) ON DELETE CASCADE
);
仓库界面:
public interface TwoWayServiceRepository extends Repository<TwoWayService, Integer> {
<S extends T> S save(S entity);
...
}
在我的单元测试中,我发现当我在 TwoWayService 上调用 findOne 时,我发现我有 4 个 Services 而不是 2 个。浏览数据库直接显示了我所期望的数据。
TwoWayService tws1 = repo.findOne(1); // get by id
assertThat(tws1.getServices().size()).isEqualTo(2); // fails, expected:<[2]> but was:<[4]>
在调试器中检查它,我在services 列表中看到了 4 个元素:我期望的两个元素,加上 2 个额外的元素,它们是预期的副本。我不明白这些是从哪里来的。为什么这些额外的对象会出现在列表中?
【问题讨论】:
标签: spring hibernate spring-data spring-data-jpa