带@NamedNativeQuery的@Loader NullPointerException

时间:2016-10-11 15:38:47

标签: java spring hibernate jpa

我有2个实体类:

@Entity
public class Product {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String title;

    private String code;
    private long price;

    @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @Loader(namedQuery = "productFields")
    private List<ProductOwnerFields> fields = new ArrayList<>();

    @OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
    private Set<ProductPhoto> photos = new HashSet<>();

    //getters and setters
}

@Entity
@NamedNativeQueries({@NamedNativeQuery(
        name = "productFields",
        resultClass = ProductOwnerFields.class,
        query = "select p.* " +
                "from productownerfields p " +
                "   left outer join templatefields t " +
                "       on p.templateField_id = t.id " +
                "where p.product_id = ? " +
                "order by t.order_field desc"
)})
public class ProductOwnerFields {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "product_id")
    private Product product;

    private String customValue;

    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "templateField_id")
    private TemplateFields templateFields;

    //getters and setters
}

和DAO:

@Repository
public class IProductDao implements ProductDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public Product find(int id) {
        return entityManager.find(Product.class, id);
    }
}

当我尝试通过find方法获取产品时,我获得了Product类的字段调用“fields”的异常: 无法评估表达式抛出'java.lang.NullPointerException'异常。

在跟踪中命名查询运行:

  

TRACE o.h.type.descriptor.sql.BasicBinder - 绑定参数[1] as   [INTEGER] - [88] DEBUG org.hibernate.loader.Loader - 结果集行:0 TRACE o.h.t.descriptor.sql.BasicExtractor - 提取值([id]:   [INTEGER]) - [361] DEBUG org.hibernate.loader.Loader - 结果行:   的EntityKey [com.inetshop.core.entities.ProductOwnerFields#361]

我该如何解决这个错误?一组ProductPhoto加载就可以了。

感谢您的帮助!

0 个答案:

没有答案