如果这些表之间没有关系,我该如何加入2个实体表?

问题描述 投票:2回答:2

我有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设置LOGS(不是User实体/只有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

如果我之间没有关系,我该如何加入2个表?我可以使用本机查询,但也许没有必要?

java hibernate jpa orm
2个回答
2
投票

更新

在查询中,当匹配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

0
投票

您可以添加ManyToOne关系

@Entity
@Table(name = "LOGS")
public class Logs implements Serializable {
    private Long id;
    private Long userId;
    private String message;

    @Getter
    @Setter
    @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.DETACH)
    @JoinColumn(name = "USER_ID")
    private User user;

}
© www.soinside.com 2019 - 2024. All rights reserved.