2

我有两个类的多对一映射(代码减少):

类别:

@Entity
public class Category {

    @Id
    @Column(name = "CATEGORY_ID")
    Long id;

    @NotNull
    String name;

子类别:

@Entity
public class Subcategory {

    @Id
    @Column(name = "SUBCATEGORY_ID")
    Long id;

    @NotNull
    @ManyToOne(targetEntity = Category.class)
    @JoinColumn(name = "CATEGORY_ID")
    Long categoryId;

    @NotNull
    String name;

当我尝试将子类别添加到现有类别时,我得到

ERROR [org.jboss.ejb3.invocation] JBAS014134: EJB Invocation failed on component SubcategoryController for method public void %package%.SubcategoryController.add(%package%.Subcategory): javax.ejb.EJBException: javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of %package%.Category.id
...
    at %package%.SubcategoryController$$$view1.add(Unknown Source)
...
    at %package%.SubcategoryController$Proxy$_$$_Weld$Proxy$.add(SubcategoryController$Proxy$_$$_Weld$Proxy$.java)
    at %package%.SubcategoryService.add(SubcategoryService.java:30)
    at %package%.SubcategoryService$Proxy$_$$_WeldClientProxy.add(SubcategoryService$Proxy$_$$_WeldClientProxy.java)
...
Caused by: javax.persistence.PersistenceException: org.hibernate.PropertyAccessException: could not get a field value by reflection getter of %package%.Category.id

我应该怎么做才能避免这个错误?

4

2 回答 2

1

在您的类别类中,它应该是这样的 OneToMany 注释:

@Entity
public class Category {    
    @Id
    @Column(name = "CATEGORY_ID")
    Long id;    
    @NotNull
    String name;        
    @OneToMany(mappedBy = "category")
    List<Subcategory> subcategories;    
}

您可能还想查看:
www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example-annotation/

于 2013-08-03T16:53:13.517 回答
0

可能发生此异常的情况:

1)数据库表名不正确或缺失:

@Entity
@Table(name = "category_table")    // name of database table
public class Category

2) 字段类与目标类不匹配:

@ManyToOne(targetEntity = Category.class)   // Target class
@JoinColumn(name = "CATEGORY_ID")
Category categoryId;                        // Target field

在您的情况下categoryId是 type Long,并且 hibernate 正在尝试将Category.class字段插入categoryId但不能。

于 2015-09-14T06:50:53.993 回答