2017-03-15 49 views
0

我有一些具有一对多 - 多对一关系的实体类。我正在使用Spring和Hibernate。Spring Data JPA Hibernate - 出现在@ManyToOne关系中的额外元素

每个TwoWayService在我的应用程序中恰好有2个Service s。

摘录:

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

    ... 
} 

我在后端使用德比。数据库模式是这样的:

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个额外的人这是预期的副本。我不知道这些来自哪里。为什么这些额外的对象出现在列表中?

回答

0

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

+0

我在setters中调用'List.set',它只是替换给定索引处的项目。 'List.add'会添加一个新的。这很奇怪,列表中的元素0&1是service1对象,元素2&3是service2对象。我试过不在构造函数中创建默认值,但结果相同。 – AlanW

相关问题