我有两个实体:
@Entity
@Table(name = "THINGS")
public class Thing {
@Id
@Column(name = "THING_PK")
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@Column(name= "NAME")
private String name;
}
和
@Entity
@Table(name = "PERSONS")
public class Person {
@Id
@Column(name = "PERSON_PK")
@GeneratedValue(strategy= GenerationType.IDENTITY)
private Long id;
@Column(name= "FIRSTNAME")
private String firstName;
@Column(name= "GROUP_ID")
private Long groupId;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "GROUP_ID", referencedColumnName = "GROUP_ID")
private List<Thing> things;
}
我不确定是否正确映射,但一般的想法如下: 如果&#34;人&#34;是属于同一群体而不是他们应该拥有相同的东西&#34;。
第一个问题:这种映射在意识形态和技术上是否正确?
如果是的话:
我使用注释动态创建数据库。它创造了我不能期望的约束。
当我执行此代码时结果:
List<Thing> thingList = new ArrayList<Thing>();
Person person = new Person();
person.setFirstName("Name1");
person.setGroupId(1L);
person.setThings(thingList);
Thing thing1 = new Thing();
thing1.setName("Name1");
thingList.add(thing1);
Thing thing2 = new Thing();
thing2.setName("Name2");
thingList.add(thing2);
entityManager.persist(person);
List<Thing> thingList2 = new ArrayList<Thing>();
Person person2 = new Person();
person2.setFirstName("Name2");
person2.setGroupId(2L);
person2.setThings(thingList2);
Thing thing3 = new Thing();
thing3.setName("Name3");
thingList2.add(thing3);
entityManager.persist(person2);
Person person3 = new Person();
person3.setFirstName("Name3");
person3.setGroupId(1L);
person3.setThings(thingList);
entityManager.persist(person3);
我收到:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.h2.jdbc.JdbcSQLException:Unique index or primary key violation: "FK_THINGS_GROUP_ID_INDEX_2 ON PUBLIC.PERSONS(GROUP_ID) VALUES (1, 2)"; SQL statement:
INSERT INTO PERSONS (FIRSTNAME, GROUP_ID) VALUES (?, ?) [23505-188]
Error Code: 23505
Call: INSERT INTO PERSONS (FIRSTNAME, GROUP_ID) VALUES (?, ?)
bind => [Name1, 1]
Query: InsertObjectQuery(Person{id=null, firstName='Name1', groupId=1, things=[Thing{id=null, name='Name1'}, Thing{id=null, name='Name2'}]})