我要做的是根据用户ID将表连接到另一个表。
我有一个用户表和一个警报历史记录表,该表具有与用户ID相关联的外键。
我使用的是Netbeans 7.4生成的实体。
用户:
@Entity
@Table(name = "Users", schema = "dbo")
public class User extends Model implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "UserID")
private Integer userID;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "userId")
private Collection<AlertHistory> alertHistoryCollection;
{ ... }
提醒记录:
@Entity
@Table(name = "Alert_History", schema = "dbo")
public class AlertHistory extends Model implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Long id;
@Basic(optional = false)
@Column(name = "user_id")
@ManyToOne(fetch = FetchType.EAGER)
private int userId;
@Basic(optional = false)
@Column(name = "message_id")
private long messageId;
@Basic(optional = false)
@Lob
@Column(name = "alerts_triggered")
private String alertsTriggered;
{...}
我期望的是,当我加载用户时,它将尝试根据userId加入AlertsHistory
表结果。但是,在运行时,AlertsHistory
集合始终为null
更新:已解决
我看错了方法。为了进行JOIN,AlertHistory期望被传递给User对象,而不仅仅是userId键。将User
字段添加到AlertHistory
模型,并将@OneToMany(mappedBy = "userId")
更改为@OneToMany(mappedBy = "user"
,然后将@JoinColumn(name="user_id", referencedColumnName="userId")
private User user;
添加到User
字段中AlertHistory
1}}让我整理出来!感谢大家的帮助。
答案 0 :(得分:0)
首先,没有人想要null
个集合,所以在User
中执行此操作:
private Collection<AlertHistory> alertHistoryCollection = new ArrayList<>();
//assuming Java 7
然后您需要User
中的AlertHistory
个实例,如下所示:
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "UserID")
private User user;