質問

What I'm trying to do is to join a table to another table based on a user id.

I have a user table, and an alerts history table that has a foreign key associated with the user's ID.

I am using entities generated by Netbeans 7.4.

User:

    @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;
     { ... }

Alert History:

    @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;
            {...}

What I would expect is that when I load a user, it will attempt to join the AlertsHistory table results based on the userId. However, at runtime, the AlertsHistory Collection is always null

Update: SOLVED

I was looking at this the wrong way. In order to do a JOIN, AlertHistory was expecting to be handed a User object, and not just the userId key. Adding a User field to the AlertHistory model, and changing the @OneToMany(mappedBy = "userId") to @OneToMany(mappedBy = "user", then adding @JoinColumn(name="user_id", referencedColumnName="userId") private User user; to that User field in AlertHistory got me sorted out! Thanks for the help everyone.

役に立ちましたか?

解決

For one thing, nobody wants null collections, so do this in User:

private Collection<AlertHistory> alertHistoryCollection = new ArrayList<>();
//assuming Java 7

Then you need the User instance in AlertHistory like this:

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "UserID")
private User user;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top