How to map objects dynamically in hibernate - java

I need help on hibernate mapping for a bean property refers to multiple classes.
In my application we are implementing permissions. These permission are not specific to certain user it may based on groups(contains list of users) and roles. So, Permissions will apply to users, roles and groups.
Following are ddl and entity classes. Please review and help me.
DDL:
--stores the application users
CREATE TABLE users (
id serial PRIMARY KEY,
name text,
CONSTRAINT uk_users_name UNIQUE (name)
);
--stores the application groups
CREATE TABLE groups (
id serial PRIMARY KEY,
name text,
CONSTRAINT uk_groups_name UNIQUE (name)
);
--stores the application roles
CREATE TABLE roles (
id serial PRIMARY KEY,
name text,
CONSTRAINT uk_roles_name UNIQUE (name)
);
--stores the application object types
CREATE TABLE app_object_types (
id serial PRIMARY KEY,
name text,
CONSTRAINT uk_app_object_types_name UNIQUE (name)
);
INSERT INTO app_object_types (name) VALUES ('USERS');
INSERT INTO app_object_types (name) VALUES ('GROUPS');
INSERT INTO app_object_types (name) VALUES ('ROLES');
CREATE TABLE app_permissions (
id serial PRIMARY KEY,
object_type_id integer REFERENCES app_object_types(id), -- To represent the object type
object_id integer, -- Objecct_id refers users -> id, groups -> id, roles - id
permission_name text,
CONSTRAINT uk_permissions UNIQUE (object_type_id, object_id, permission_name)
);
Entity Classes:
#Entity
#Table(name = "users")
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getName() {
return name;
}
public void setName(int name) {
this.name = name;
}
}
#Entity
#Table(name = "groups")
public class Groups {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getName() {
return name;
}
public void setName(int name) {
this.name = name;
}
}
#Entity
#Table(name = "roles")
public class Roles {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getName() {
return name;
}
public void setName(int name) {
this.name = name;
}
}
#Entity
#Table(name = "app_object_types")
public class AppObjectTypes {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getName() {
return name;
}
public void setName(int name) {
this.name = name;
}
}
#Entity
#Table(name = "app_permissions")
public class AppPermissions {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne
private String permissionName;
#ManyToOne
private AppObjectTypes appObjectTypes;
private int objectId;
private Class<?> dependentObject;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPermissionName() {
return permissionName;
}
public void setPermissionName(String permissionName) {
this.permissionName = permissionName;
}
public AppObjectTypes getAppObjectTypes() {
return appObjectTypes;
}
public void setAppObjectTypes(AppObjectTypes appObjectTypes) {
this.appObjectTypes = appObjectTypes;
}
public int getObjectId() {
return objectId;
}
public void setObjectId(int objectId) {
this.objectId = objectId;
}
public Class<?> getDependentObject() {
return dependentObject;
}
public void setDependentObject(Class<?> dependentObject) {
this.dependentObject = dependentObject;
}
}
I want to map user (or) group (or) role bean object to AppPermissions -> dependentObject using hibernate. I don't know it is possible or not please help me.

I would suggest you consider the use of #Inheritance here on your AppPermission entity in order to specialize each subclass based on the dependent object types.
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
#DiscriminatorColumn(name = "OBJECT_TYPE")
public class AppPermission {
#Id
#GeneratedValue
private Long permissionId;
private String name;
#Column(name = "OBJECT_TYPE", insertable = false, updatable = false)
private String objectType;
}
#Entity
#DiscriminatorValue("USER")
public class UserAppPermission extends AppPermission {
#ManyToOne(optional = false)
private User user;
}
#Entity
#DiscriminatorValue("ROLE")
public class RoleAppPermission extends AppPermission {
#ManyToOne(optional = false)
private Role role;
}
#Entity
#DiscriminatorValue("GROUP")
public class GroupAppPermission extends AppPermission {
#ManyToOne(optional = false)
private Group group;
}
The first difference here with these mappings from yours is that your AppPermission table will be constructed differently from your current schema and would look like the following (note 4 tables):
Table: AppPermission
id NOT NULL IDENTITY(1,1)
name VARCHAR(255)
OBJECT_TYPE VARCHAR(31)
Table: UserAppPermission
id NOT NULL BIGINT (FK -> AppPermission)
user_id NOT NULL BIGINT (FK -> User)
Table: RoleAppPermission
id NOT NULL BIGINT (FK -> AppPermission)
role_id NOT NULL BIGINT (FK -> Role)
Table: GroupAppPermission
id NOT NULL BIGINT (FK -> AppPermission)
group_id NOT NULL BIGINT (FK -> Group)
The whole point of a database is to help us maintain referential integrity. That's why when a table depends on a row from another table, the dependent table rows that relate to the row you wish to remove should be removed first to avoid constraint violations. This is precisely why I have split the relations into separate tables and here I've defined each relation as "optional=false" so that basically it represents a join-table.
Another additional benefit is that if your AppPermission has attributes you need to store specific to the type of dependent object, you can freely add those attributes to the subclass and those attributes are stored separately in that specific subclass's table.
This setup also eliminates your AppObjectType table because that is now driven as part of Hibernate's discriminator pattern. Be aware that if you have other "object-types" you'll need to introduce their specific implementations too with this setup.
Lastly, I exposed (which you don't have to) the OBJECT_TYPE as an non-insertable and non-updatable field because Hibernate manages that for you. But I've exposed it allowing you to make polymorphic queries and determine the object type of the resulting object without having to perform instanceof checks if you wish.

Related

What is the real purpose of #OneToOne in Spring boot hibernate?

I have two entities named Users and Dependents. I want to establish a OneToOne relationship between these two entities. As the real meaning of OneToOne states that -
Every user in the Users entity should have one and only one dependent.
And every dependent in the Dependents entity should only be related to
one and only one user.
But when I add #OneToOne to Dependents entity it does not stop me from adding two dependents to the same user. What is the real use of #OneToOne
or any other relationship annotations like #ManyToMany, #OneToMany, #ManyToOne?
Users.java
#Entity
#Table
public class Users {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String teamName;
private Integer salary;
public Users() {
}
public Users(Integer id, String name, String teamName, Integer salary) {
this.id = id;
this.name = name;
this.teamName = teamName;
this.salary = salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
}
Dependents.java
#Entity
#Table
public class Dependents {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String relationship;
#OneToOne
private Users user;
public Dependents() {
}
public Dependents(int id, String name, String relationship) {
this.id = id;
this.name = name;
this.relationship = relationship;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRelationship() {
return relationship;
}
public void setRelationship(String relationship) {
this.relationship = relationship;
}
public Users getUser() {
return user;
}
public void setUser(Users user) {
this.user = user;
}
}
And in my DependentsService.java I am saving the Dependents object like-
public Dependents addNewDependent(Integer userId, Dependents dependent) {
dependent.setUser(usersRepository.getOne(userId));
return dependentsRepository.save(dependent);
}
Here I am fetching the user from the Users entity with the passed userId and storing it in Dependents object. When I pass the same userId for two or more dependents it will fetch the same user from Users entity and store it in Dependents entity. This violated OneToOne relationship. Can someone please explain to me, how can I achieve true OneToOne relationship? And also please explain what is the true purpose of relationship annotations like - #OneToOne, #OneToMany, #ManyToOne and #ManyToMany?
From Hibernate documentation:
From a relational database point of view, the underlying schema is identical to the unidirectional #ManyToOne association, as the client-side controls the relationship based on the foreign key column.
...
A much more natural mapping would be if the Phone were the parent-side, therefore pushing the foreign key into the PhoneDetails table. This mapping requires a bidirectional #OneToOne association
...
When using a bidirectional #OneToOne association, Hibernate enforces the unique constraint upon fetching the child-side. If there are more than one children associated with the same parent, Hibernate will throw a org.hibernate.exception.ConstraintViolationException.
So you should use a bidirectional one-to-one association.
Additional info: The best way to map a #OneToOne relationship with JPA and Hibernate
Hibernate won't do any extra checks to make sure, the record already exists. It is your responsibility to write the code which satisfies the OneToOne relation (it depends on your UI screens as well). If you still want to throw some exception, make your primary key as Foreign key in dependent table. Then you get DB exception.

Hibernate Cannot add or update a child row: a foreign key constraint fails

When I'm trying to save object into database I got error:
java.sql.SQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`smartphones`.`smartphone`, CONSTRAINT `fk_smartphone_resolution1` FOREIGN KEY (`resolution_id`) REFERENCES `resolution` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
First thing is I have wrong name of references column in Smartphone class but I checked and it looks well. Maybe someone figure out what is the reason of this issue?
Short database screenshot
SQL script to create smartphone table
CREATE TABLE IF NOT EXISTS `smartphones`.`smartphone` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NULL DEFAULT NULL,
`resolution_id` INT(11) NOT NULL,
...other
PRIMARY KEY (`id`, `resolution_id`),
UNIQUE INDEX `id_UNIQUE` (`id` ASC),
INDEX `fk_smartphone_resolution1_idx` (`resolution_id` ASC),
CONSTRAINT `fk_smartphone_resolution1`
FOREIGN KEY (`resolution_id`)
REFERENCES `smartphones`.`resolution` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
Smartphone class but with one relationship object.
package com.project.model;
import javax.persistence.*;
#Entity
public class Smartphone {
private int id;
private String name;
private Resolution resolutionId;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.PERSIST)
#JoinColumn(name = "resolution_id", referencedColumnName = "id", nullable = false)
public Resolution getResolutionId() {
return resolutionId;
}
public void setResolutionId(Resolution resolutionId) {
this.resolutionId = resolutionId;
}
}
[Edit: Parsing smartphone model and saving into database]
#RequestMapping(value = { "apple" }, method = RequestMethod.GET)
public String parseApple(ModelMap model) {
try {
String appleData = Utilities.getResourceAsString(this, "json/apple.json");
JSONArray array = new JSONArray(appleData);
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
for (int i = 0; i < array.length(); i++) {
Smartphone smartphone = new Smartphone();
String resolutionValue = array.getJSONObject(i).getString("resolution");
String resolution_w = resolutionValue.split(" ")[0];
String resolution_h = resolutionValue.split(" ")[2];
Resolution resolution = new Resolution();
resolution.setHeight(Integer.valueOf(resolution_h));
resolution.setWidth(Integer.valueOf(resolution_w));
resolution.setTypeId(typeService.findByCode(session, Resolution.serialId));
session.save(resolution);
smartphone.setResolutionId(resolution);
//other
session.save(smartphone);
break;
}
transaction.commit();
sessionFactory.close();
} catch (IOException e) {
e.printStackTrace();
}
return "index";
}
[Edit: Added] Resolution class:
#Entity
public class Resolution {
public static final int serialId = 106;
private int id;
private Integer height;
private Integer width;
private Type typeId;
private Collection<Smartphone> resolutionId;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "height")
public Integer getHeight() {
return height;
}
public void setHeight(Integer height) {
this.height = height;
}
#Basic
#Column(name = "width")
public Integer getWidth() {
return width;
}
public void setWidth(Integer width) {
this.width = width;
}
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "type_id", referencedColumnName = "id", nullable = false)
public Type getTypeId() {
return typeId;
}
public void setTypeId(Type typeId) {
this.typeId = typeId;
}
#LazyCollection(LazyCollectionOption.FALSE)
#OneToMany(mappedBy = "resolutionId")
public Collection<Smartphone> getResolutionId() {
return resolutionId;
}
public void setResolutionId(Collection<Smartphone> resolutionId) {
this.resolutionId = resolutionId;
}
}
Almost well. You have to add above getId() method for Resolution class and similar code below. Probably your resolution object has always 0 as id after save method call.
#Column(name = "id", unique = true, nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
You're trying to add/update a row to resolution that does not have a valid value for the id field based on the values stored in smartphone.
You must first insert the row to your resolution table.
Add
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Annotations in Model class.

Select from two table from hibernate?

I have two tables in db employee and department as:
CREATE TABLE test.employee (
EMPID int(10) unsigned NOT NULL DEFAULT '1',
Name varchar(45) NOT NULL DEFAULT '1',
DEPTID int(10) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (EMPID),
KEY FK_employee_1 (DEPTID),
CONSTRAINT FK_employee_1 FOREIGN KEY (DEPTID) REFERENCES department (DEPTID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE test.department (
DEPTID int(10) unsigned NOT NULL AUTO_INCREMENT,
Name varchar(45) NOT NULL,
PRIMARY KEY (DEPTID)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
And my mapping classes are as below:
Employee2.java
#Entity
#Table(name="EMPLOYEE")
public class Employee2 {
#Id #GeneratedValue
#Column(name="EMPID")
private String ID;
#Column(name="Name")
private String Name;
#Column(name="DEPTID")
private String DepartmentID;
public Employee2(String iD, String name, String departmentID){
ID = iD;
Name = name;
DepartmentID = departmentID;
}
public Employee2(){
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getDepartmentID() {
return DepartmentID;
}
public void setDepartmentID(String departmentID) {
DepartmentID = departmentID;
}
#OneToOne
#JoinColumn(table = "DEPARTMENT", name = "DEPTID", referencedColumnName="DEPTID")
private Department2 ec;
public Department2 getEc() {
return ec;
}
public void setEc(Department2 ec) {
this.ec = ec;
}
}
Department2.java
#Entity
#Table(name="DEPARTMENT")
public class Department2 {
#Id #GeneratedValue
#Column(name="DEPTID")
private String ID;
#Column(name="Name")
private String Name;
public Department2(String iD, String name) {
ID = iD;
Name = name;
}
public Department2(){
}
public String getID() {
return ID;
}
public void setID(String iD) {
ID = iD;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
I want to select from two tables with join as EMPLOYEE.DEPTID = DEPARTMENT.DEPTID
I dont want to write query.
Here is how I m doing it in test class
tx = session.beginTransaction();
Criteria criteria = session.createCriteria(Employee2.class, "employee").
createCriteria("employee.ec", JoinType.INNER_JOIN);
List<Equipment2> rows = criteria.list();
System.out.println(rows.size());
tx.commit();
But I m getting following exception
Failed to create sessionFactory object.org.hibernate.AnnotationException: Cannot find the expected secondary table: no DEPARTMENT available for com.cts.sm.Employee2
Exception in thread "main" java.lang.ExceptionInInitializerError
I m using Hibernate 4.2
Can you please help me as what I m missing in this.
As suggested by #jpprade
Make the following change
#ManyToOne
#JoinColumn(name ="DEPTID", updatable = false, insertable = false)
private Department2 ec;
//getter setter
Thanks
N G

Make ElementCollection Set<String> generate surrogate primary key?

In JPA's CollectionTable example
#Entity
public class Person {
#Id protected long id;
#ElementCollection
#Column(name="name")
protected Set<String> nickNames = new HashSet();
}
It creates a join table Person_nickNames with such values :
It is hard for edit/delete values . We cannot use tools such as phpmyadmin to click the row and edit the value because there is no PK.
Is it possible for JPA to generate a surrogate primary key in the join table ?
environments : JPA 2 with Hibernate 4.3 implementation
Hi Smallufo
Write #GeneratedValue(strategy = GenerationType.AUTO) after #Id
This will make a surrogate primary key.
I think that should be possible. Added an ID column as IDENTITY in the PERSON_NICKNAMES table and with the below Person mapping class I am able to generate unique IDs in Person_nicknames table.
#Entity
#Table(name="Person")
public class Person {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String name;
#ElementCollection
#CollectionTable(name="Person_Nicknames", joinColumns=#JoinColumn(name="person_id"))
#Column(name="name")
private Set<String> nickNames;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<String> getNickNames() {
return nickNames;
}
public void setNickNames(Set<String> nickNames) {
this.nickNames = nickNames;
}
}
When I save the person and nickname records I see following in person_nicknames table.
> ij> select * from Person_nicknames;
ID |PERSON_ID |NAME
1 |6 |nName0
2 |6 |nName1
3 |7 |nName0
4 |7 |nName1

Hibernate OneToOne Relationship: Unable to delete the child table

Let's say we are living in a world a person could have only one vehicle(Forgive me for my lame example)
Let's say I have this UserDetails Class
public class UserDetails {
#Id
#GeneratedValue
#Column(name = "USER_ID")
private int id;
#Column(name = "USER_NAME")
private String name;
#OneToOne
private Vehicle vehicle;
public Vehicle getVehicle() {
return vehicle;
}
public void setVehicle(Vehicle vehicle) {
this.vehicle = vehicle;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
And this is My Vehicle class
#Entity
public class Vehicle {
#Id
#GeneratedValue
private long vechile_id;
private String vehicleName;
public long getVechile_id() {
return vechile_id;
}
public void setVechile_id(long vechile_id) {
this.vechile_id = vechile_id;
}
public String getVehicleName() {
return vehicleName;
}
public void setVehicleName(String vehicleName) {
this.vehicleName = vehicleName;
}
}
Upon Saving it to the database it works fine, but when I went to delete the Table for vehicle this error showed up on my workbench
NOTE That there are only one entries on both UserDetails and Vehicle Table.
ERROR 1217: Cannot delete or update a parent row: a foreign key constraint fails
SQL Statement:
drop table `hibernate`.`vehicle`
How come am I not allowed to drop the table? Should I delete The UserDetails table first?
If you'd delete the Vehicle table, that would make the UserDetails table loose it's referential integrity because the vehicle column's foreign keys would point to nowhere. Drop the fk constraint or the vehicle column from UserDetails then you can delete the table you want.

Categories