我有 2 个实体
@Entity
@Table(name = "USER")
public class User implements Serializable {
private Long id;
private String username;
}
和
@Entity
@Table(name = "LOGS")
public class Logs implements Serializable {
private Long id;
private Long userId;
private String message;
}
该实体没有关系。当LOGS
填充时,我没有User
实体(但我有userId
),并且我在中设置了
(不是userId
>LOGSUser
实体/仅Long userId
)。
当我在网页上显示用户日志时,我需要显示 LOGS
的所有字段:
id userId message
1 1 message1
2 1 message2
3 2 message3
4 2 message4
但我需要将 userId
替换为 UserName
:
id user message
1 Bill message1
2 Bill message2
3 John message3
4 John message4
如果两个表之间没有关系,如何连接?我可以使用 native 查询,但也许没有必要?
最佳答案
已更新
在查询中,当您匹配 where 子句中的列时,应使用“旧”样式进行连接:
1)为投影字段创建类:
package org.myapp;
public class UserLogs{
private Long id;
private String username;
private String message;
public UserLogs(Long id, String username, String message){
this.id = id;
this.username = username;
this.message = message;
}
}
2)执行查询
String query =
" select new org.myapp.UserLogs"+
"(l.id, u.username, l.message) "+
" from Logs l, User u"+
" where l.userId = u.id";
List<UserLogs> userLogs = session.createQuery(query)
.list();
// process list
关于java - 如果两个实体表之间没有关系,如何连接这些表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41848625/