我有这个问题
这些是我的表
这是我的代码" Compra"
@Entity
@Table(name = "compra")
public class Compra implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "codigo", unique = true, nullable = false)
private int codigo;
@ManyToOne
@JoinColumn(name = "codProveedor", nullable = false)
private Proveedor proveedor;
@Column(name = "tipoComprobante", nullable = false)
private String tipoComprobante;
@Temporal(TemporalType.DATE)
@Column(name = "fechaFactura", nullable = false)
private Date fechaFactura;
@Temporal(TemporalType.DATE)
@Column(name = "fechaLlegada", nullable = false)
private Date fechaLlegada;
@Column(name = "serie", nullable = false)
private String serie;
@Column(name = "numero", nullable = false)
private int numero;
@Column(name = "importe", nullable = false)
private double importe;
@Column(name = "vigencia", nullable = false)
private boolean vigencia = true;
@ElementCollection
private List<DetalleCompra> lstDetalle = new ArrayList<DetalleCompra>();
// getters and setters ...
这是我的代码&#34; DetalleCompra&#34;
@Entity
@Table(name = "detalleCompra")
public class DetalleCompra implements Serializable {
@Id
@GeneratedValue(generator = "gen")
@GenericGenerator(name = "gen", strategy = "foreign", parameters = @Parameter(name = "property", value = "compra"))
@Column(name = "codCompra", nullable = false)
private int codCompra;
@ManyToOne
@JoinColumn(name = "codPresentacion", nullable = false)
private Presentacion presentacion;
@Column(name = "imei", nullable = false)
private String imei;
@Column(name = "simcard", nullable = false)
private String simcard;
getters and setters ...
一切看起来都不错,但是当我想保存时,我有这个问题
org.hibernate.TransientObjectException:object引用未保存的瞬态实例 - 在刷新之前保存瞬态实例:DetalleCompra
很明显,因为当我想保存Compra和DetalleCompra时,第二个表期望fk值 public void registrar(Compra compra) {
try {
session = HibernateUtil.getSessionFactory().openSession();
trans = session.beginTransaction();
session.save(compra);
trans.commit();
} catch (Exception e) {
trans.rollback();
throw e;
} finally {
session.close();
}
}
表格&#34; compra&#34;生成得好但是对于另一个表没有识别出这个值自动生成,为什么?,我该如何解决?
答案 0 :(得分:0)
@ElementCollection
定义基本类型或可嵌入类的实例的集合。 如果要通过a映射集合,则必须指定 收集表。
您使用错误的注释来表示关系。 Compra
和DetalleCompra
之间存在一对多关系。
您应该将@ElementCollection
注释更改为@OneToMany
。不要忘记指定连接列@JoinColumn(name="codCompra")
。我假设Presentacion
已正确映射。
另见