In hibernate I have created a one-to-many relationship between user and roles. More then one user can be associated with a role, but a user can be associated with just one role.
In User class, I have
@ManyToOne
@JoinColumn(name = "role_id")
private Role role_id;
In Role Class, I have
@OneToMany(mappedBy="role_id", fetch=FetchType.LAZY)
private Collection<User> userList = new ArrayList<User>();
If I am saving a new user as :
{
"userName" : "Michael",
"role_id" : {
"id" : 8
}
}
It saves user even when role table has no role with id as 8( and no entry is done in role table). I want that I should get a referential integrity error whenever I am saving a user with a non existent role. What should I change?
My Users table is created as:
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`email` varchar(255) DEFAULT NULL,
`mobile` varchar(255) DEFAULT NULL,
`username` varchar(255) NOT NULL,
`role_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_abcdef` (`role_id`),
CONSTRAINT `FK_abcdef` FOREIGN KEY (`role_id`) REFERENCES `role` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;