我有以下两个实体,
用户
@Entity
@EqualsAndHashCode
public class User extends BaseEntity{
@Getter @Setter
private String msid;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "sender")
@Getter
private List<Media> sentList;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "receiver")
@Getter
private List<Media> receivedList;
protected User(){
super();
}
public User(String yguid) {
this();
this.yguid = yguid;
this.receivedList = new ArrayList<>();
this.sentList = new ArrayList<>();
}
}
媒体
@Entity
@EqualsAndHashCode
public class Media extends BaseEntity{
@Getter @Setter
private String mediaId;
@Getter @Setter
private String url;
@ManyToOne
@JoinColumn(name="sender")
@Getter @Setter
private User sender;
@ManyToOne
@JoinColumn(name="receiver")
@Getter @Setter
private User receiver;
public Media() {
super();
}
public Media(String mediaId, String url, User sender, User receiver) {
this();
this.mediaId = mediaId;
this.url = url;
this.sender = sender;
this.receiver = receiver;
}
}
两者都继承自BaseEntity
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private final Long id;
public BaseEntity() {
id = null;
}
}
我想为用户获取所有媒体。这是我的代码
public List<Media> getReceivedMediaForUser(User user){
Session session = sessionFactory.openSession();
Query query = session.createQuery("FROM Media m WHERE m.receiver = :user");
//parse query to get result
session.close();
//
return null;
}
这不编译,有人可以帮我形成正确的查询并获得结果。我是Spring和Hibernate的新手。
答案 0 :(得分:-1)
您可以按照以下所示进行操作(这是一个不遵循解决方案的示例。根据您的要求实施解决方案),
Query query = session.createSQLQuery(
"select * from stock s where s.stock_code = :stockCode")
.addEntity(Stock.class)
.setParameter("stockCode", "7277");
List result = query.list();
您的解决方案可能是
Session session = sessionFactory.openSession();
Query query = session.createQuery("select * FROM Media m WHERE m.receiver = :user")
.addEntity(Media.class)
.setParameter("user", "xyz");
List result = query.list();
session.close();