如何使用postgreSQL和java eclipselink在连接表中插入数据?

时间:2015-10-10 15:47:05

标签: java postgresql join orm eclipselink

我的数据库中有3个表:

create table characters(
name varchar(255) primary key,
class varchar(55) NOT NULL,
race varchar(55) not null,
level int not null
);

create table users(
user_name varchar(255) primary key,
balance int not null,
first_name varchar(255) not null,
last_name varchar(255) not null,
iban varchar(255) not null,
character_slots int not null,
last_payment date not null,
months_payed int not null,
password varchar(255) not null,
banned varchar(1) not null
);

create table owns(
name varchar(255) references characters(name),
user_name varchar(255) references users(user_name)
);

正如您所看到的,“拥有”表是一个连接表。

我正在使用java eclipselink。当我在用户和角色中插入数据时,没有发生在“拥有”表中。

我无法在java中手动插入数据,因为它只显示了Users.java和Characters.java类。在我的Character.java类中,我看到了这段代码,也许这将帮助您找到我需要的解决方案。

@JoinTable(name = "owns", joinColumns = {
    @JoinColumn(name = "name", referencedColumnName = "name")}, inverseJoinColumns = {
    @JoinColumn(name = "user_name", referencedColumnName = "user_name")})
@ManyToMany
private Collection<Users> usersCollection;

我在数据库中插入值的方式如下:

Characters c1 = new Characters(t_char.getText(), cb_class.getValue(), cb_race.getValue(), 1);
persist(c1);

1 个答案:

答案 0 :(得分:0)

编辑你的映射:

@JoinTable(name = "owns", joinColumns = {
@JoinColumn(name = "name", referencedColumnName = "name")}, inverseJoinColumns = {
@JoinColumn(name = "user_name", referencedColumnName = "user_name")})
@ManyToMany(mappedBy = "user")
private Collection<Users> usersCollection;

和您的&#34;用户&#34;应该是:

@ManyToOne
@JoinTable(name = "owns", joinColumns = {
@JoinColumn(name = "name", referencedColumnName = "name")}, inverseJoinColumns = {
@JoinColumn(name = "user_name", referencedColumnName = "user_name")})
public User getUser() {
    return user;
}