我正面臨單向onetomany映射的一些問題。 我表用戶和Rubrica:單向OneToMany映射問題
User (
scode double precision NOT NULL,
...
CONSTRAINT utenti_pkey PRIMARY KEY (scode)
)
Rubrica (
id serial NOT NULL,
id_owner integer NOT NULL,
id_contact integer NOT NULL,
CONSTRAINT rubrica_pkey PRIMARY KEY (id),
CONSTRAINT rubrica_fk01 FOREIGN KEY (id_owner)
REFERENCES users (scode) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION,
CONSTRAINT rubrica_fk02 FOREIGN KEY (id_contact)
REFERENCES users (scode) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
不要介意用戶雙PKEY。這是客戶的表格,我無法修改它。 Rubrica店主,用戶和聯繫人之間的關係,也是一組用戶。 用戶映射如下:
@SuppressWarnings("serial")
@Entity
@Table(name = "utenti", schema = "public")
public class User implements Serializable {
@Id
@Column(name = "scode", unique = true, nullable = false)
private Integer scode;
...
}
好的。這是問題出現的時間。如果我映射Rubrica這樣的:
public class Rubrica2 implements Serializable {
@Id
@Column(name = "id", nullable = false, unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_owner", nullable = false, unique = true, referencedColumnName = "scode")
private User owner;
@OneToMany(fetch = FetchType.EAGER)
@JoinColumn(name = "id_contact", nullable = false, updatable = false, insertable = true, referencedColumnName = "scode")
private Set<User> relations = new HashSet<User>();
...
}
JBoss的給了我這個例外在部署:
Caused by: org.hibernate.MappingException: Unable to find column with logical name: scode in org.hibernate.mapping.Table(public.rubrica) and its related
supertables和輔助表
如果我映射Rubrica這樣:
public class Rubrica2 implements Serializable {
@Id
@Column(name = "id", nullable = false, unique = true)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "id_owner", nullable = false, unique = true, referencedColumnName = "scode")
private User owner;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "scode")
private Set<User> relations = new HashSet<User>();
...
}
我在運行時得到了不好的行爲。如果我運行此代碼
r = new Rubrica2();
q2.setParameter("id", ownerID);
User owner = (User) q2.getSingleResult();
r.setOwner(owner);
q2.setParameter("id", contactID);
User u = (User) q2.getSingleResult();
r.getRelations().add(u);
entityManager.persist(r);
我得到這個異常:
Hibernate: insert into public.rubrica (id_owner) values (?)
11:08:19,440 DEBUG [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (EJB default - 7)
ERROR: null values in column "id_contact" violates not-null constraint [n/a]: org.postgresql.util.PSQLException:
ERROR: null values in column "id_contact" violates not-null constraint
我按照理論指出here約一對多單向的。 我使用JPA2.0,Hibernate4(由JBoss7.1.1.Final提供)和PostgresSQL。
是類名Utente是用戶? – Gayathri
@Gayathri是的。更新謝謝。 – Francesco