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

时间:2010-11-14 22:39:37

标签: java jpa entity

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

我希望获得具有特定SKU值的所有ProductDescriptor。像这样:

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;

...

1 个答案:

答案 0 :(得分:13)

这样的事情:

@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() );
}