现有用户实体,相关代码如下:
@Entity
@Table(name = "t_users")
public class User extends Model {
@Id
@Column(name = "users_id")
@GeneratedValue(strategy = GenerationType.AUTO)
public Long userId;
...
}
以及好友关系实体,相关代码如下:
@Entity
@Table(name = "t_relationship")
public class Relationship extends Model {
@Id
@Column(name = "rs_id")
public Long relationshipId;
@Column(name = "rs_fromuser", nullable = false)
public User fromUser;
@Column(name = "rs_touser", nullable = false)
public User toUser;
...
}
从SQL书写来考虑,只需要在关系实体的两个Column上添加外键约束即可。但却不知道在JPA中应该怎么完成。
个人数据库相关的知识比较欠缺,在这两个实体是不是多对多关系上存在疑问。
一个用户可以对应多个好友关系,一个好友关系对应固定的两个用户。应该说是n..2这种关系吗?
已经尝试使用@ManyToMany注解,但是我使用的Play 2框架和Ebean没有生成相对应的SQL语句。
// User model类
@Entity
@Table(name = "t_users")
public class User extends Model {
@Id
@Column(name = "u_id")
@GeneratedValue(strategy = GenerationType.AUTO)
public Long userId;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "fromUser")
public List<Relationship> followUsers;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "toUser")
public List<Relationship> followers;
...
}
@Entity
@Table(name = "t_relationship")
public class Relationship extends Model {
@Id
@Column(name = "rs_id")
public Long relationshipId;
@JoinColumn(name = "rs_fromuser", nullable = false, updatable = false)
@ManyToOne(optional = false)
public User fromUser;
@JoinColumn(name = "rs_touser", nullable = false, updatable = false)
@ManyToOne(optional = false)
public User toUser;
...
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。