我正在尝试创建两个实体(公民,城镇),并在它们之间建立关系 公民与一个城镇相连,一个城镇可以有几个公民 我不知道什么样的关系是好的。
我试过了:
@Entity
@Table(name = "citizen")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Citizen implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column(name = "lastname", nullable = false)
private String lastname;
@OneToOne
@JoinColumn
private Town ownTown;
//getter and setter
}
@Entity
@Table(name = "town")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class Town implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@NotNull
@Column(name = "town_name", nullable = false)
private String townName;
//getter and setter
}
但是我得到了
引起: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: 键'town_id'重复输入'1'
当我尝试插入公民时。
这种关系有什么问题?
答案 0 :(得分:0)
@Entity
public class Citizen implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
@JoinColumn( name = "town_id", referencedColumnName = "id" )
private Town town;
//getter and setter
}
@Entity
public class Town implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@OneToMany( mappedBy = town )
private List<Citizen> citizens;
//getter and setter
}
答案 1 :(得分:0)
一个城镇有很多公民。这是一对多的关系。
创建一个Citizen表,并从Town表上面的Town表中将TownId作为外键。这样,您就可以指定许多公民在一个城镇。
以下是SpringData中多对一关系的example。这个狗窝(用户)的例子可以有多个狗。根据您的需要定制它。