I'm trying to implement a Keyword search functionality that returns a List of Keyword entities based on a field text match.
Right now, the 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%";
returns all matching photos for a given keyword search. I'd like to have this adapted to a @NamedQuery
with the following Entity objects:
@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
}
and
@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
}
This creates a join table photo_keywords
, rather than a JoinColumn.
What I've tried so far with the Keyword
entity:
@NamedQueries({
@NamedQuery(
name = "findKeywordByName",
query = "SELECT keyword from Keyword k WHERE k.keyword = :keyword"
)
})
which is executed via
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;
}
This returns the Keyword, but with the photos
property being null. This is to be expected, since I'm only selecting the keyword
property. How can I adapt the SQL query above to a @NamedQuery
?