0

I have recently asked quite similar question here, but answer does not solve my new 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 "user_id" was created not as Integer like in database, but:

@JoinColumn(name="user_id")
private User user;

So now when i try to create new "Book" like this:

public String saveData() {
if(!validate()){
...
if (book != null) {
        System.out.println(getUser());
        setName(book.getName());
        System.out.println("Post3");
        setSurname(book.getSurname());
        setAdress(book.getAdress());
        setSize(book.getSize());
        setContact(book.getContact());
        setPrice(book.getPrice());
        setOthers(book.getOthers());
        setIsReady(book.getIsReady());
        setRooms(book.getRooms());
        setUser(book.getUser());
        System.out.println(user);
    }
private boolean validate() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        boolean result = false;
        System.out.println("validate");

        if (ctx.getMessageList().isEmpty()) {


            book.setName(name.trim());
            book.setSurname(surname.trim());
            book.setAdress(adress.trim());
            book.setSize(size.trim());
            book.setContact(contact.trim());
            book.setPrice(price);
            book.setOthers(others.trim());
            book.setIsReady(isReady.trim());
            book.setRooms(rooms);
            book.setUser(user);
            result = true;
        }

        return result;
    }

...
    bookDAO.create(book);

I'm getting

Column 'user_id' cannot be null

I am not sending 'user_id' in form but I have it stored in session BUT as integer.

So now when I am trying to force that int into the setUser I get an error that I can use only User objects there.

So my question is, are there any ways to convert Integer(which my id_user is) into the User?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Macjej
  • 117
  • 1
  • 10

2 Answers2

1

You need to get User object from your database using the user_id in your session.
If you are using JPA entitymanager

User user = entityManager.find(User.class, user_id);  
book.setUser(user);
Edu Okafor
  • 11
  • 3
0

You must select User by user_id from your database, or just

User user = new User();
user.setUserId(id_user);
book.setUser(user);
Sanat Serikuly
  • 189
  • 3
  • 16