开发者

Unneeded column added trying to set up OneToMany relationship

I'm trying to set up a OneToMany relationship between an author and his posts with author as the foreign key and username as primary key, using Java EE 6 and toplink+eclipselink as persistence provider.

Here is what i have:

Annotations in class User

@Id
@NotNull(message = "Please enter username")
@Size(min = 8, max = 40)
@Column(unique=true, nullable=false) 
private String username;

...

private Collection<BlogEntry> blg = new ArrayList<BlogEntry>();

    @OneToMany(cascade = {CascadeType.ALL}, mappedBy="user")
    public Collection<BlogEntry> getBlg() {
        return blg;
    }

Annotations in class BlogEntry

    @NotNull
    @Size(min = 8, max = 40)
    private String author;

... 

private User user;

    @ManyToOne()
    public User getUser() {
        return user;
    }

The problem is that a new column(USER_USERNAME) is added when inserting values into BlogEntry Table, which of course shows an error of the field not existing in BlogEntry:

INSERT INTO BLOGENTRY (ID, CONTENT, AUTHOR, TITLE, CREATED, USER_USERNAME) VALUES (?, ?, ?, ?, ?, ?)
    bind => [301, xxxxxxxx, xxxxxxxx, xxxxxx开发者_如何学编程xx, 2011-06-07 12:49:07.014, null]

I would be very glad to learn why such a column is added or what to fix to get a simple OneToMany relationship using username and author fields. I searched and tried many tutorials but seems i'm missing something.


If you want to use an existing AUTHOR column as a foreign key, you need to map many-to-one relationship to that column as follows:

@ManyToOne()
@JoinColumn(name = 'author')
private User user;

Note that in typical case you can remove a separate author field from the class, since now it can be obtained as user.getUsername(). If you need both fields in the class, you need to mark one of them as read-only with insertable = false, updateable = false, because only one read-write field can be mapped to a particular column.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜