2012-10-24 39 views
0

我目前在播放框架1.2.4 JPA有问题。Playframework发送2查询获取查询

我需要在一个单独的数据库中有一个UserOptions模型,并且想要在一个查询中只需要它就会加入它。

在这个查询中,我想加载选项并通过搜索我发现只能通过使用连接查询来完成。

如果我使用eager而不是oder懒惰,通过使用User.findById()并且选项和用户在一个查询中找到,一切都会好起来的。

但是,当我使用“左连接提取”查询时,play会发送两个查询。因此,继承人查询:

User.find(" 
    SELECT 
     user 
    FROM 
     User user 
    LEFT JOIN FETCH 
     user.options options 
    WHERE 
     user.id = ? 
", Long.parseLong(id)).first(); 

这里的模型:

@Entity 
public class User extends Model 
{ 

    @OneToOne(mappedBy = "user", fetch = FetchType.LAZY) 
    public UserOptions options; 

    // ... 

} 

@Entity 
public class UserOptions extends Model 
{ 

    @OneToOne(fetch = FetchType.LAZY) 
    public User user; 

} 

的问题是,为什么打发送两个查询抓取查询?

在此先感谢

+0

另一个问题:当我使用findById时,缓存请求。当我用查询使用find时,play不会。也许这是同一个问题。如何制作播放缓存用户? – michiruf

回答

0

好吧,自己动手。查询仍然是一样的。

问题是,默认情况下自定义查询没有被缓存。所以我使用这段代码来提供一个数据库缓存(仅适用于当前的请求)。

 // Get database cache instance 
     EhCacheImpl cache = EhCacheImpl.getInstance(); 

     // Get cached user 
     User user = (User)cache.get("UserWithOptions_"+id); 

     // Check whether a user is cached 
     if(user == null) 
     { 
      // Get the user 
      user = User.find("SELECT user FROM User user LEFT JOIN FETCH user.options options WHERE user.id = ?", Long.parseLong(id)).first(); 
     } 

     // Refresh cache 
     cache.add("UserWithOptions_"+id, user, 0); 

愿力量与你同在!