使用MySQL DB在Hibernate单向中进行一对一映射?

时间:2018-09-27 06:47:57

标签: java mysql hibernate

是Hibernate和MySQL的新手,我有两个表,例如 OFFER_TABLE OFFER_LIKES_DISLIKES

OFFER_TABLE列

OFR_ID(PK)
OFR_MSG

OFFER_LIKES_DISLIKES列

OFFER_LIKES_DISLIKES_ID
OFR_ID(FK)
LIKE
DISLIKE

我想映射OFFER_TABLE和OFFER_LIKES_DISLIKES,通过OFFER_TABLE访问OFFER_LIKES_DISLIKES数据。我正在使用一对一映射,但无法正常工作。

休眠注释映射Java类

Offers.class

@Id
@GeneratedValue
@Column(name = "OFR_ID", length = 11, nullable = false)
private int offer_id;

@OneToOne
@JoinColumn(name="OFR_ID", unique = true)
@OneToOne(cascade = CascadeType.ALL)
private MessageLikeDislikesDAO likeDislikes;

LikeDislike.class

@GeneratedValue
@Column(name="LIKES_DISLIKES_ID", length = 11, nullable = false)
private int likes_dislikes_id;

@Expose
@Column(name="OFR_ID", length = 11, nullable = false)
private int offer_id;

当我获得要约数据时,想要点赞和不喜欢与其关联的数据。在LikeDislike表中,OFR_ID是UNIQUE。被一对一使用。但是我没有得到LikeDislike的数据。哪一种是获取该数据的最佳方法。帮我解决这个问题。

1 个答案:

答案 0 :(得分:2)

有很多问题:

  1. 您正在创建与DAO的关联,而不是与实体的关联
  2. 您将要约的ID存储在LikeDislike实体中,而不是存储与要约实体的关联
  3. 您是说有一个名为OFR_ID的连接列,并引用了OFFER表中的LikeDislike实体。
  4. 您不尊重Java命名约定
  5. 您要在同一字段上设置两个OneToOne批注

映射应为:

优惠:

@Id
@GeneratedValue
@Column(name = "OFR_ID", length = 11, nullable = false)
private Integer offerId;

@OneToOne(mappedBy = "offer", cascade = CascadeType.ALL)
private LikeDislike likeDislike;

LikeDislike:

@GeneratedValue
@Column(name="LIKES_DISLIKES_ID", length = 11, nullable = false)
private Integer likeDislikeId;

@Expose
@OneToOne
@JoinColumn(name="OFR_ID", length = 11, nullable = false)
private Offer offer;

Relevant documentation