Andrea Robinson Andrea Robinson - 4 months ago 8
SQL Question

Insert a value of 1 on users table that is referencing admin table hibernate

I am trying to save a value of 1 on users table that is referencing an admin table with a foreign key of adminId on the users table

In my User.java I have this

@OneToOne
@JoinColumn(name = "adminId")
Admin admin;


this is the getter and setter for the above mapping to the user.java referencing the admin table

public Admin getAdmins() {
return admin;
}

public void setAdmin(Admin id) {

this.admin = id;
}


In my DAO class of SpringBoot application, I am persisting to the users table like this

public void save(User user) {
Admin admin = (Admin)getSession().createQuery("from Admin a where a.adminId = ?")
.setParameter(0, 1);
user.setAdmin(admin);

getSession().save(user);
}


EDITTED:
this is how I am trying to save a user

public void save(User user) {
long id = 1 ;

Admin admin = (Admin)getSession().createQuery("from Admin a where a.adminId = ?").setParameter(0, 1).list().get(0);
user.setAdminz(admin);

getSession().save(user);
}


this is my controller code for saving action

@RequestMapping(value = "/create-user", method = RequestMethod.POST)
public ModelAndView createUser(HttpServletRequest request,
HttpServletResponse response,
@RequestParam String name,
@RequestParam String email) {
try {
// create new user object
User user = new User();
user.setName(name);
user.setEmail(email);
user.setTimestamp(new Date().getTime());

// save user in db (if new)
if (_userDao.getByEmail(email) == null) {
_userDao.save(user);
}


when I try to save I get this error

com.xxx.MainController [0;39m [2m:[0;39m Exception in creating user:


I have modified my mapping to this not to accept nullable

@OneToOne
@JoinColumn(name = "adminId",nullable = false)
Admin admin;


If I remove nullable = false annotation, NULL value is saved into the adminId field of the user table.

Please what am I doing wrong? Kindly assist.

Answer

You have to execute your query

Admin admin = (Admin)getSession().createQuery("from Admin a where a.adminId = ?").setParameter(0, 1);

Your IDE should warn you about this line because you cant cast Hibernate Query to your Admin type as long as if you didn't implement it to your Admin class, if you did that, that is so wrong...

This code is not best practice for getting single element but you have to execute your query with list() method. and get your element from list.

Admin admin = (Admin)getSession().createQuery("from Admin a where a.adminId = ?").setParameter(0, 1).list().get(0)
//Warning! If list is empty, there will be an error.

If you want to pick single element from db with using hibernate(and map with an entity) i recommend you to use this code.

Admin admin = getSession().get(Admin.class, 1); 
Comments