【发布时间】:2015-12-20 14:11:39
【问题描述】:
我有 3 个班级,即 Satislar、Urunler 和 Musteriler
在 Satislar 类中,有 2 个外键:urunid 和 musteriid
每个Satislar 对象都有一个Urunler 对象和一个Musteriler 对象。
所以我的Satislar 类中需要两个不同的OneToOne 映射。首先是Urunler,其次是Musteriler。
当我向数据库添加一个新的 Satislar 对象时,我将使用现有的 Musteriler 对象和 Urunler 对象。代码不得创建新的Musteriler、Urunler 对象。
为了实现这一点,我使用了
(insertable= false, updatable=false)
但我不能将 Urunler 和 Musteriler 对象设置为 Satislar 对象。它说:
列不允许空值。插入失败。
我认为我的注释有问题。
这是我的代码块。
...
Session session = null;
Urunler urun = gelenUrunler.get(tblUrunler.getSelectedRow());
Musteriler musteri = gelenMusteriler.get(cmbMusteriler.getSelectedIndex());
System.out.println(musteri.getId() + "asd " + urun.getId());
Satislar satis = new Satislar();
satis.setUrun(urun);
satis.setMusteri(musteri);
satis.setAdet(Integer.valueOf(txtAdet.getText().trim()));
satis.setTarih(new Date());
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(satis);
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Satış sırasında hata oluştu." + e);
} finally {
session.close();
}
...
坐骑类:
...
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@Column(name = "urunid", insertable = false, updatable = false)
private Integer urunid;
@Basic(optional = false)
@Column(name = "adet")
private Integer adet;
@Basic(optional = false)
@Column(name = "musteriid", insertable = false, updatable = false)
private Integer musteriid;
@Basic(optional = false)
@Column(name = "tarih")
@Temporal(TemporalType.TIMESTAMP)
private Date tarih;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "urunid", insertable = false, updatable = false)
private Urunler urun;
public Urunler getUrun() {
return urun;
}
public void setUrun(Urunler urun) {
this.urun = urun;
}
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "musteriid", insertable = false, updatable = false)
private Musteriler musteri;
public Musteriler getMusteri() {
return musteri;
}
public void setMusteri(Musteriler musteri) {
this.musteri = musteri;
}
...
【问题讨论】:
标签: java hibernate hibernate-mapping cascade one-to-one