简体   繁体   中英

Java EE Query two tables

So here is my problem: I have two tables: User and Book, they are in ManyToOne relation. The Book table has attribute called user_id that connects both tables. Using Eclipse I generated entity classes and work on them without problem until now. The problem is, when I want to get "books" that have speciffic user_id I get an error:

java.lang.IllegalArgumentException: Parameter value [1] did not match expected type [model.User (n/a)]

The "value" is an id that I'm getting from session, I tried it in both int and String.

part of 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;
}

part of BookBB:

    public List<Book> getFullListWithId(){
    HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
    Integer str =(Integer)session.getAttribute("userId");
    return  bookDAO.getFullListWithId(str);
}

part of 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;

part of 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;

Thank you so much for any help possible.

I believe query should be select b from Book b WHERE b.user.idUser = :id

You might want to take a look at hibernate docs

https://docs.jboss.org/hibernate/orm/3.6/reference/en-US/html/queryhql.html {Chapter 16}

You have two options.

1) you pass an User object with the id as a parameter to the query (I prefer that solution):

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) you pass the id as a parameter:

Query query = em.createQuery("select b from Book b WHERE b.user.id = :id");
if (id!= null) {    
     query.setParameter("id", id);           
}

Please note the b.user.id in the query

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM