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

标签 java mysql spring hibernate

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

相关文章:

java - 在 Java 中填充二维数组

java - 如何在android中单击按钮时将值添加到数组

java - Spring 多个打开的连接

java - 字符串比较时获取空指针异常

java - 如何重写 equals() 方法

php - Mysql concat不等表字段

php - 通过用户角色 PHP 登录后重定向

mysql - 如果我检查日期 2019-01-12 是否在 12 月到 1 月的日期范围内,查询将给出空结果

java - 如何在 Spring 中强制属性文件中的属性?

java - Spring Integration - 控制自动启动