在Hibernate中有没有办法返回一个对象或对象列表,这些对象或对象列表中的派生数据不作为对象的一部分保存在表中?
例如,如果您有一个推文对象,如下所示:
long id;
String message;
long profile_id;
//non-persisted properties
long numLikes;
boolean isLiked;
然后你有另一个对象来跟踪谁喜欢推文,如
long id;
long liked_id;
long profile_id;
boolean liked;
我(我可以)如何设置推文对象,以便在tweet对象中看到喜欢的数量?查询看起来像
Select *, count(likes1.id) as numLikes, isNull(liked1.liked,0) as isLiked from tweets
left join (select id,liked_id from likes where liked_id = tweets.id) as likes1 on tweets.id = likes1 .liked_id
left join (select liked_id,liked from likes where profile_id = :authenticated_User) as liked1 on tweets.id = liked1.liked_id
where.....
无论如何,我可以在一个对象中填充所有这些,而不在tweets对象的每个属性上使用addScalar?如果不是这种设置的正确方法是什么?
(假设所有属性都在sql查询中正确命名,数据按预期返回,我知道我的示例中有些内容会中断。)
答案 0 :(得分:0)
我建议这样做(仅在你不使用DTO的情况下使用它):
1)创建类TweetRecordFilter以帮助过滤TweetRecord
public class TweetRecordFilter(){
private long tweetId;
private long personId;
private long profileId;
private boolean liked;
//create setters and getters for all attributes mentioned above
}
2)创建查找TweetRecords的方法(你说他们跟踪谁喜欢什么)
public List<TweetRecord> findTweetRecordByFilter(TweetRecordFilter tweetrecordFilter){
// return found records that have properties that were set to tweetRecordFilter
// I suggest do a select using PreparedStatement
/* here write that code*/
}
3)创建选择推文的方法
public Tweet findTweetById(int tweetId){
// find tweet that has tweetId and say you have found one, let's call it "foundTweet"
// I suggest do a select using PreparedStatement
/* here write that code*/
// find all tweetRecord that have specific profile_id
TweetRecordFilter tweetRecordFilter = new TweetRecordFilter();
tweetRecordFilter.setProfileId(foundTweet.getProfileId);
tweetRecordFilter.setLiked(true);
List<TweetRecord> tweetRecords = findTweetRecordByFilter(tweetRecordFilter);
// set the number of likes for tweet
if(tweetRecords != null){
foundTweet.setLikesCount(tweetRecords.size());
}
return foundTweet;
}
所有这些都放在一个实际的例子中:
int tweetId = 1;
Tweet tweet = findTweetById(1);
int numberOfLikes = tweet.getNumberOfLikes;
有关preparedStatement的更多信息,您可以找到here。