休眠中的 OnetoOne 和 OneToMany

OnetoOne and OneToMany in hibernate

我有两个实体类 用户和钱包数据 我想通过注释将一个用户与多个钱包建立关系,但我不知道如何。还有我想通过位于用户实体中的签名字段传递的关系。

@Entity(name = "wallet_data")
public class WalletData implements Serializable
{

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name = "amount")
    private Double amount;
    @Column(name = "currency")
    private String currency;
    @JoinColumn(table = "user",referencedColumnName = "signature")
    private User user; //Each wallet know who is his owner user

@Entity
@Table(name = "user")
@XmlRootElement
@NamedQueries(
        {
            @NamedQuery(name = "User.findAll", query = "SELECT u FROM User u"),
            @NamedQuery(name = "User.findById", query = "SELECT u FROM User u WHERE u.id = :id"),
            @NamedQuery(name = "User.findByUsername", query = "SELECT u FROM User u WHERE u.username = :username"),
            @NamedQuery(name = "User.findByPassword", query = "SELECT u FROM User u WHERE u.password = :password"),
            @NamedQuery(name = "User.authorize", query = "SELECT u FROM User u WHERE u.password = :password and u.username = :username")
        })
public class User implements Serializable
{

    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 = "username")
    private String username;
    @Basic(optional = false)
    @Column(name = "password")
    private String password;
    @Column(name = "signature")
    private String signature;
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    @OneToOne(targetEntity = UserData.class)
    private UserData userId;
    @OneToMany(targetEntity = WalletData.class, cascade = CascadeType.ALL,mappedBy = "id")
    private Set<WalletData> wallets; //The set contain all wallets of the current user

您忘记了 WalletData.user 上的 @ManyToOne 注释。

mappedBy 属性应该是 user,因为这是构成关联另一方的字段。

文档中描述了双向 OneToMany 关联。阅读:http://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/#d5e5564