gpt4 book ai didi

java - 返回非持久数据作为对象的一部分

转载 作者:行者123 更新时间:2023-11-30 23:07:17 25 4
gpt4 key购买 nike

在 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;

我将如何(可以)设置推文对象,以便我可以在推文对象中看到点赞数?查询看起来像

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 查询中正确命名并且数据按预期返回我知道我的示例中有些东西会中断。)

最佳答案

我的建议是这样做(仅在您不使用 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 .

关于java - 返回非持久数据作为对象的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21319370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com