java – JPA:查询根据实体类中定义的外键值获取结果?

Netbean 6.9从此sql Server 2008表生成以下JPA实体类:

我想获得具有特定SKU值的所有ProductDescriptors.像这样的东西:

SELECT * FROM ProductDescriptors WHERE SKU='something'

给定实体类,获得结果的Java代码是什么?

谢谢.

@Entity
@Table(name = "ProductDescriptors")
@NamedQueries({
    @NamedQuery(name = "ProductDescriptors.findAll",query = "SELECT p FROM ProductDescriptors p"),@NamedQuery(name = "ProductDescriptors.findByDescriptorID",query = "SELECT p FROM ProductDescriptors p WHERE p.descriptorID = :descriptorID"),@NamedQuery(name = "ProductDescriptors.findByLanguageCode",query = "SELECT p FROM ProductDescriptors p WHERE p.languageCode = :languageCode"),@NamedQuery(name = "ProductDescriptors.findByTitle",query = "SELECT p FROM ProductDescriptors p WHERE p.title = :title"),@NamedQuery(name = "ProductDescriptors.findByIsDefault",query = "SELECT p FROM ProductDescriptors p WHERE p.isDefault = :isDefault"),@NamedQuery(name = "ProductDescriptors.findByBody",query = "SELECT p FROM ProductDescriptors p WHERE p.body = :body")})
public class ProductDescriptors implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @Basic(optional = false)
    @Column(name = "DescriptorID")
    private Integer descriptorID;
    @Basic(optional = false)
    @Column(name = "LanguageCode")
    private String languageCode;
    @Basic(optional = false)
    @Column(name = "Title")
    private String title;
    @Basic(optional = false)
    @Column(name = "IsDefault")
    private boolean isDefault;
    @Basic(optional = false)
    @Column(name = "Body")
    private String body;
    @JoinColumn(name = "SKU",referencedColumnName = "SKU")
    @ManyToOne(optional = false)
    private Products products;

解决方法

像这样的东西:
@PersistenceContext( unitName = "youPersistenceUnitHere" )
private EntityManager _entityManager;

public List<ProductDescriptors> getProductDescriptorsBySku( String sku ) {
   Query query = _entityManager.createQuery( "Select ProductDescriptors from ProductDescriptors pd where pd.products.sku = ?1" );
   query.setParameter( 1,sku );
   return new ArrayList<ProductDescriptors>( query.getResultList() );
}

相关文章

ArrayList简介:ArrayList 的底层是数组队列,相当于动态数组。与 Java 中的数组相比,它的容量能动态增...
一、进程与线程 进程:是代码在数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位。 线程...
本文为博客园作者所写:&#160;一寸HUI,个人博客地址:https://www.cnblogs.com/zsql/ 简单的一个类...
#############java面向对象详解#############1、面向对象基本概念2、类与对象3、类和对象的定义格式4、...
一、什么是异常? 异常就是有异于常态,和正常情况不一样,有错误出错。在java中,阻止当前方法或作用域...
Collection接口 Collection接口 Collection接口 Collection是最基本的集合接口,一个Collection代表一组...