Java休眠:@OneToMany协会不起作用

时间:2016-02-29 08:28:21

标签: java spring hibernate spring-mvc

在我的代码中,oneToMany类和customer类之间存在item关系。这意味着,客户可能拥有一件或多件商品。 这是客户代码:

@Entity
@Data

public class customer {

    @Id
    @GeneratedValue
    int id;

    String name;
    String lastname;

    @Embedded
    Address address;

    @OneToMany
     @Column(name="ITEM_ID")
    List<item> item;    
}

它是项目类:

@Entity
@Data

public class item {

    @Id
    @GeneratedValue
    int id;

    String name;
    String Serialnumber;
    int price;

    @ManyToOne
    customer customer;

}

然后我做了一些测试来尝试在模型中查询。

insert into item(id,name,Serialnumber,price) values(1,'bike','123',200);
insert into item(id,name,Serialnumber,price) values(2,'car','123',200);


insert into customer(id,name,lastname,Country,City,Street,No,item_id) 
values(1,'Salman','Lashkarara','Iran','Tehran','Shariati','12',1);

insert into customer(id,name,lastname,Country,City,Street,No,item_id) 
values(2,'Saba','Lashkarara','Iran','Tehran','Shariati','12',2);


insert into customer(id,name,lastname,Country,City,Street,No,item_id) 
values(3,'Saba','Lashkarara','Iran','Tehran','Shariati','12',1);

但是当我运行我的代码时,我面临以下错误:

Column "ITEM_ID" not found; SQL statement:
insert into customer(id,name,lastname,Country,City,Street,No,item_id) values(1,'Salman','Lashkarara','Iran','Tehran','Shariati','12',1)

请特别注意,它是java mvc-spring应用程序,我使用代码创建模型,因此没有数据库可以检查字段item_id

如您所见,我已添加了@Column(name="ITEM_ID")来定义列。

4 个答案:

答案 0 :(得分:1)

您必须将@JoinColumn用于关联列:

@OneToMany
@JoinColumn(name="ITEM_ID")
List<item> item; 

答案 1 :(得分:0)

其他一些选择

@OneToMany(cascade=CascadeType.All, fetch=FetchType.EAGER)
@JoinColumn(name="ITEM_ID")
List<item> item; 

在Item类

@ManyToOne(mappedBy="item")
customer customer;

答案 2 :(得分:0)

你可以这样做我还有user课程和bcr课程,一个用户有很多bcr,所以下面的代码会帮助你

<强> bcr.java

@ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_who_enter_demand", nullable = false)
    public User getUserByUserWhoEnterDemand() {
    return this.userByUserWhoEnterDemand;
    }

    public void setUserByUserWhoEnterDemand(User userByUserWhoEnterDemand) {
    this.userByUserWhoEnterDemand = userByUserWhoEnterDemand;
    }

<强> user.java

@OneToMany(fetch = FetchType.LAZY, mappedBy = "userByUserWhoEnterDemand")
    public Set<BudgetControlRegister> getBudgetControlRegistersForUserWhoEnterDemand() {
    return this.budgetControlRegistersForUserWhoEnterDemand;
    }

    public void setBudgetControlRegistersForUserWhoEnterDemand(Set<BudgetControlRegister> budgetControlRegistersForUserWhoEnterDemand) {
    this.budgetControlRegistersForUserWhoEnterDemand = budgetControlRegistersForUserWhoEnterDemand;
    }

答案 3 :(得分:0)

您无法在没有表格的情况下映射表格列:

@Entity
@Table(name = "ITEM_TABLE")
public class item {
...
 @ManyToOne(fetch=FetchType.LAZY)
 @JoinColumn(name = "CUSTOMER_ID_ITEM_TABLE") 
 private customer customer;
...
}

@Entity
@Table(name = "CUSTOMER_TABLE")
public class customer {
...
  @OneToMany
  @Column(name="ITEM_ID")
  List<item> item;    
}