Spring数据:OneToOne关系问题

时间:2016-04-07 14:42:59

标签: jpa spring-data

我正在开发一个webapp(Spring J2EE / angularjs)

我想在两个实体之间建立关系:
公民(id,lastName,city)
city(id,cityName)

一个公民只住在一个城市。

我需要从公民那里找到一座城市。 我不需要找一个城市的公民。

我做到了:

@Entity
@Table(name = "citizen")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Citizen implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "last_name")
    private String lastName;

    @OneToOne
    private City city;
}



@Entity
@Table(name = "city")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class City implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "city_name")
    private String cityName;
}

在数据库中我插入了数据。公民1,2和3与城市1相关联  和Citizen 4与City 2相关联

当我尝试加载所有公民时,我收到错误: 找到了多个具有给定标识符的行:1,对于类:com.myApp.rh.domain.Citizen

我的实体出了什么问题?

由于

1 个答案:

答案 0 :(得分:0)

您的Citizen实体中似乎缺少@JoinColumn注释。

@Entity
@Table(name = "citizen")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Citizen implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "last_name")
    private String lastName;

    @OneToOne
    @JoinColumn(name = "id", unique = true)
    private City city;
}



@Entity
@Table(name = "city")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class City implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "city_name")
    private String cityName;
}