所以这是我的问题:
我有两个表:User 和 Book,它们是 ManyToOne 关系。 Book
表具有连接两个表的名为 user_id
的属性。
到目前为止,我使用 Eclipse 生成了实体类并毫无问题地处理它们。
问题是,当我想获得具有特定 user_id
的“书籍”时,出现错误:
java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [model.User (n/a)]
“值”是我从 session 中获得的一个 id,我在 int 和 String 中都试过了。
BookDao 的一部分:
public List<Book> getFullListWithId(Integer id) {
List<Book> list = null;
Query query = em.createQuery("select b from Book b WHERE b.user = :id");
if (id!= null) {
query.setParameter("id", id);
}
try {
list = query.getResultList();
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
部分 BookBB:
public List<Book> getFullListWithId(){
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
Integer str =(Integer)session.getAttribute("userId");
return bookDAO.getFullListWithId(str);
}
Book.java的一部分
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id_offer")
private int idOffer;
private String adress;
private String contact;
@Column(name="is_ready")
private String isReady;
private String name;
private String others;
private int price;
private int rooms;
private String size;
private String surname;
//bi-directional many-to-one association to User
@ManyToOne
@JoinColumn(name="user_id")
private User user;
User.java的一部分
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id_user")
private int idUser;
private String login;
private String password;
//bi-directional many-to-one association to Book
@OneToMany(mappedBy="user")
private List<Book> books;
非常感谢您提供的任何帮助。
最佳答案
你有两个选择。
1) 您将带有 id 作为参数的用户对象传递给查询(我更喜欢该解决方案):
Query query = em.createQuery("select b from Book b WHERE b.user = :user");
User u = new User();
u.setId(id)
query.setParameter("user", u);
2) 你将 id 作为参数传递:
Query query = em.createQuery("select b from Book b WHERE b.user.id = :id");
if (id!= null) {
query.setParameter("id", id);
}
请注意查询中的b.user.id
关于Java EE 查询两个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35506679/