java onetoone,Java:Hibernate @OneToOne映射

I'm trying to get Hibernate @OneToOne annotations working and not having much success here...

Let's say I've got a table called status that looks like this:

+------------------------------------------------+

| status |

+------------------------------------------------+

| id | frn_user_id | frn_content_id | status |

+----+-------------+----------------+------------+

| 1 | 111 | 0 | "active" |

+----+-------------+----------------+------------+

| 2 | 0 | 222 | "inactive" |

+----+-------------+----------------+------------+

And I've got an entity for User that looks like this:

@Entity

@Table(name = "user")

public class User {

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

@Column(name = "id", nullable = false)

private Integer id;

@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "userId")

private Status status;

// getters and setters

}

And a similar one for Content, and another entity for Status that looks like this:

@Entity

@Table(name = "status")

public class Status {

@Id

@GeneratedValue(strategy = GenerationType.AUTO)

@Column(name = "id", nullable = false)

private Integer id;

@Column(name = "frn_user_id")

private Integer userId;

@Column(name = "frn_content_id")

private Integer contentId;

@Column(name = "status")

private String status;

// getters and setters

}

When I perform a read on User, I expect that User.getStatus() will return a Status object with id=1. Instead, I get an AnnotationException: "Referenced property not a (One|Many)ToOne: Status.userId in mappedBy User.status"

I've poured through docs, tutorials and examples here on SO, but everything I've tried so far has failed.

Also worth noting: This should support a one-to-zero-or-one relationship, as some user and content records will not have a reference in the status table.

Any help would be greatly appreciated!

解决方案

Your Status entity must not have properties userId and contentId of type Integer, mapped with @Column. It must have properties user and content of type User and Content, mapped with @OneToOne:

public class User {

@OneToOne(mappedBy = "user")

private Status status;

// ...

}

public class Status {

@OneToOne

@JoinColumn(name = "frn_user_id")

private User user;

// ...

}

A user has one status. A status has one user.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值