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

Posted

技术标签:

【中文标题】JPA:查询以根据实体类中定义的外键值获取结果?【英文标题】:JPA: query to get results based on value of foreign key defined in the entity class? 【发布时间】:2011-05-09 23:16:34 【问题描述】:

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

我想获取所有具有特定 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】:

类似这样的:

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

【讨论】:

另一个有点类似的问题:***.com/questions/4180905/jpa-join-table-syntax 好的,我在那里添加了一个解决方案。正如我在那里评论的那样,我不知道您需要涉及 products 表\实体集;所以我把它留了下来。如果你这样做,请发表评论,我会再看一遍。

以上是关于JPA:查询以根据实体类中定义的外键值获取结果?的主要内容,如果未能解决你的问题,请参考以下文章

如何在模板中获取表单的外键值?

根据当前日期+时间查询 JPA 实体以获取实例的最佳方法是啥?

Spring Data JPA 查询结果返回至自定义实体

Spring Data JPA 多个实体类表联合视图查询

一个映射实体中的外键为空

如何编写一个查询,根据 ms 访问的子表中的外键获取信息?