Spring Data JPA Hibernate - 出现在@ManyToOne关系中的额外元素

时间:2017-03-15 15:09:52

标签: spring hibernate spring-data spring-data-jpa

我有一些具有一对多 - 多对一关系的实体类。我正在使用Spring和Hibernate。

每个TwoWayService在我的申请中都有2 Service个。

摘录:

@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);

    ...
}

在我的单元测试中,我发现当我在findOne上调用TwoWayService时,我发现我有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个额外的元素,它们是预期的副本。我不知道这些来自哪里。为什么这些额外的对象出现在列表中?

1 个答案:

答案 0 :(得分:0)

我不确定,但我认为,这是因为你在构造函数中添加了2个服务,在每个setter中添加了1个服务。总计4个。您测试服务量,是您想要测试的吗?