【问题标题】:PropertyAccessException: could not get a field value by reflection getterPropertyAccessException:无法通过反射 getter 获取字段值
【发布时间】:2013-08-03 16:17:56
【问题描述】:

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

类别:

@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

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

【问题讨论】:

    标签: java hibernate many-to-one


    【解决方案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/

    【讨论】:

    • 我分析了给定的示例,发现将Long categoryId 更改为Category category 就足够了,但这并不能解决我的问题。是否有任何解决方案(我不需要父类中的孩子列表)?
    • @OneToMany 字段是可选的,如果你不使用它们,hibernate 不会产生异常。
    【解决方案2】:

    可能发生此异常的情况:

    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 的类型为 Long,并且休眠尝试将 Category.class 字段插入 categoryId 但不能。

    【讨论】:

      猜你喜欢
      • 2013-08-15
      • 2015-12-08
      • 2014-12-03
      • 2019-04-22
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多