将SQL查询转换为JPA NamedQuery

时间:2014-11-24 19:09:35

标签: mysql hibernate jpa named-query

我正在尝试实现关键字搜索功能,该功能会根据字段文本匹配返回关键字实体列表。

现在,查询

select * from photo_keywords pk
inner join keywords k on pk.photo_id = k.keyword_id
inner join photos p on pk.keyword_id = p.photo_id
where k.keyword LIKE "%$SOME_SEARCH_VALUE%";

返回给定关键字搜索的所有匹配照片。我希望将其改编为@NamedQuery以及以下实体对象:

@Entity
@Table(name = "keywords")
public class Keyword implements Serializable{

    @Id
    @Column(name = "keyword_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column
    private String keyword;

    @ManyToMany(mappedBy = "keywords")
    private List<Photo> photos;

    //getters and setters
}

@Entity
@Table(name = "photos")
public class Photo implements Serializable{

    @Id
    @Column(name = "photo_id", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "photo_name", nullable = false)
    private String photoName;

    @Column(name = "photo_path", nullable = false)
    private String photoPath;

    @Column(name = "upload_date", nullable = false)
    private Date uploadDate;

    @Column(name = "view_count", nullable = false)
    private int viewCount;

    @Column(name = "capture_date", nullable = false)
    private Date captureDate;

    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "photo_metadata")
    @MapKeyColumn(name = "metadata_name")
    @Column(name = "metadata_value")
    private Map<String, String> photoMetadata;

    @ManyToMany
    @JoinTable(name = "photo_keywords",
        joinColumns = @JoinColumn(name = "keyword_id"),
        inverseJoinColumns = @JoinColumn(name = "photo_id"))
    public List<Keyword> keywords;

    //getters and setters

}

这会创建一个连接表photo_keywords,而不是JoinColumn。

到目前为止我使用Keyword实体尝试了什么:

@NamedQueries({
    @NamedQuery(
            name = "findKeywordByName",
            query = "SELECT keyword from Keyword k WHERE k.keyword = :keyword"
    )
})

通过

执行
public Keyword findKeywordByString(String keyword){
    Keyword thisKeyword;
    Query queryKeywordExistsByName = getEntityManager().createNamedQuery("findKeywordByName");
    queryKeywordExistsByName.setParameter("keyword", keyword);

    try {

        thisKeyword = new Keyword((String) queryKeywordExistsByName.getSingleResult());

    } catch (NoResultException e){
        thisKeyword = null;
    }

    return thisKeyword;
}

返回关键字,但photos属性为null。这是可以预料的,因为我只选择了keyword属性。如何将上面的SQL查询调整为@NamedQuery

0 个答案:

没有答案