Composite key joins in hibernate in java - java

I am using hibernate to persist two tables,Project and Department.
Department table has a composite primary key DeptCompID.
#Embeddable
public class DeptCompID implements Serializable
{
#Column(name = "DeptID")
private int DeptID;
#Column(name = "RoleID")
private int RoleID;
//getters and setters
}
#Entity
public class Department implements Serializable
{
#EmbeddedId
private DeptCompID id;
private String name;
#OneToOne(mappedBy="department",targetEntity = Project.class)
private Project pro;
//getters and setters
}
#Entity
public class Project
{
#Id
private int ProId;
#OneToOne(targetEntity = Department.class)
#MapsId("DeptID")
#JoinColumns({
#JoinColumn(name = "RoleID", referencedColumnName = "RoleID"),
#JoinColumn(name = "DeptID", referencedColumnName = "DeptID")
})
private Department department;
//getters and setters
}
Code to persist the tables
Department department = new Department();
department.setName("HR");
DeptCompID cpk=new DeptCompID();
cpk.setRoleID(10);
cpk.setDeptID(60);
department.setId(cpk);
Project pro=new Project();
pro.setDepartment(department);
pro.setProId(10);
department.setPro(pro);
session.save(department);
session.save(pro);
Everytime I persist the tables Project and Department the DeptID column in Project table is always null when it should be 60.
why is #MapsId("DeptID") not working?Could some provide a resolution.

Related

How to build one to many relationship with different entities which have a composite key with Hibernate, JPA?

I want to build entity classes for the following relationship. I want an entity ProductWiseCustomer which has a composite key. Those key also mapped with Product and Customer entities. How to achieve the purpose?
So far what I have done.
Product.java
#Entity
#Table(name = "product")
public class Product {
#Id
private Long productId;
private String productName;
private Decimal productPrice;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = CustomerProductCompound.class)
private Set<CustomerProductCompound> customerProductCompound;
//Constructor
//Setter-getter
}
Customer.java
#Entity
#Table(name = "customerinfo")
public class CustomerInfo {
#Id
private Long customerId;
private String customerName;
private Boolean isActive;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, targetEntity = CustomerProductCompound.class)
private Set<CustomerProductCompound> customerProductCompound;
//Constructor
//Setter-getter
}
CustomerProductCompound.java
#Embeddable
public class CustomerProductCompound
{
#ManyToOne
#JoinColumn(name = "customerId")
private CustomerInfo customerInfo;
#ManyToOne
#JoinColumn(name = "productId")
private Product product;
//Constructor
//Setter-getter
}
While running the application getting the following error:
Use of #OneToMany or #ManyToMany targeting an unmapped class: com.auth.model.CustomerInfo.customerProductCompound[com.auth.model.CustomerProductCompound].
One solution is to use a composite identifier with #EmbeddableId.
#Entity
public class ProductWiseCustomer {
#EmbeddedId
private ProductCustomerKey key;
}
#Embeddable
public class ProductCustomerKey {
#ManyToOne(fetch = FetchType.LAZY)
private Customer customer;
#ManyToOne(fetch = FetchType.LAZY)
private Product product;
}
Please see the hibernate documentation:
https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#identifiers-composite-aggregated
CustomerProductCompound as you have defined just the primary key of ProductWiseCustomer. Your collections inside CustomerInfo and Product must contain ProductWiseCustomer items, not its key.
#Entity
#Table(name = "product")
public class Product {
#Id
private Long productId;
private String productName;
private Decimal productPrice;
#OneToMany(mappedBy = "product", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<ProductWiseCustomer> productWiseCustomers;
}
#Entity
#Table(name = "customerinfo")
public class CustomerInfo {
#Id
private Long customerId;
private String customerName;
private Boolean isActive;
#OneToMany(mappedBy = "customer", cascade = CascadeType.ALL, fetch = FetchType.EAGER, orphanRemoval = true)
private Set<ProductWiseCustomer> productWiseCustomers;
}
Notice I added the mappedBy property in the annotations. It needs to point to the property name on the other side that refers to this object. The JPA name, not the SQL name. targetEntity is rarely necessary, and I've suggested orphanRemoval, so that if you remove one from the set, you don't have to manually delete it for it to go away.
As for the ProductWiseCustomer, you do need the same key as shown by Modular Coder
#Embeddable
public class ProductCustomerKey {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "customerId)
private Customer customer;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "productId")
private Product product;
}
But I recommend you use #IdClass instead of #EmbeddedId
#Entity
#IdClass(ProductCustomerKey.class)
public class ProductWiseCustomer {
#ManyToOne(fetch = FetchType.LAZY) // should be lazy here
#JoinColumn(name = "customerId)
private Customer customer;
#ManyToOne(fetch = FetchType.LAZY) // should be lazy here
#JoinColumn(name = "productId")
private Product product;
private OffsetDateTime createDate;
private String remarks;
// getters, setters
}

JPA, Composite Key consisted of foreign key and table column members

Greetings to the community,
I am struggling all day to find a solution to the issue below.
The scenario is the following, I have a table
---TABLE_ONE---
INT ID
VARCHAR NAME
PRIMARY_KEY (ID)
and my other table consisted of three columns which consist together a composite key
---TABLE_TWO---
INT TABLE_ONE_ID (FK -> TABLE_ONE.ID)
VARCHAR NAME
VARCHAR EMAIL
PRIMARY_KEY(TABLE_ONE_ID, NAME, EMAIL)
The relationship I want to achieve is that the TABLE_ONE entity will
have a list of objects from the TABLE_TWO (one-to-many relationship).
I tried to do this with as shown below.
#Entity
#Table(name = "TABLE_ONE")
public class TableOne {
#Column(name="id")
private int id;
#Column(name="name")
private String name
#OneToMany(fetch = FetchType.EAGER, mappedBy = "tableOne")
private List<TableTwo> tableTwoList;
//getters, setters, constructors
}
#Entity
#Table(name = "TABLE_TWO")
public class TableTwo {
#EmbeddedId
private TableTwoCompositeId tableTwoCompositeId;
#ManyToOne
#JoinColumn(name = "TABLE_ONE_ID", referencedColumnName = "ID", insertable = false, updatable = false)
private TableOne tableOne;
//getters, setters, constructors
}
#Embeddable
public class TableTwoCompositeId {
#Column(name = "TABLE_ONE_ID")
public Integer provider;
#Column(name = "NAME")
public String name;
#Column(name = "EMAIL")
public String email;
//getters, setters, constructors
}
However, I'm getting javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet and Caused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist when a TableOne object is retrieved from the database.
Thanks in advance for any help!
I think you need several minor changes:
TableOne.id needs an #Id annotation
The type of TableTwoCompositeId.provider should match the type of TableOne.id
TableTwo.tableOne needs a #MapsId annotation to indicate it maps TableTwoCompositeId.provider
Here is how the code should look:
#Entity
#Table(name = "TABLE_ONE")
public class TableOne {
#Id
#Column(name="id")
private int id;
#Column(name="name")
private String name
#OneToMany(fetch = FetchType.EAGER, mappedBy = "tableOne")
private List<TableTwo> tableTwoList;
//getters, setters, constructors
}
#Entity
#Table(name = "TABLE_TWO")
public class TableTwo {
#EmbeddedId
private TableTwoCompositeId tableTwoCompositeId;
#MapsId("provider") // maps provider attribute of embedded id
#ManyToOne
#JoinColumn(name = "TABLE_ONE_ID", referencedColumnName = "ID", insertable = false, updatable = false)
private TableOne tableOne;
//getters, setters, constructors
}
#Embeddable
public class TableTwoCompositeId {
#Column(name = "TABLE_ONE_ID")
public int provider;
#Column(name = "NAME")
public String name;
#Column(name = "EMAIL")
public String email;
//getters, setters, constructors
}

How to convert this UML to JPA entities

I have this UML diagram.
And I tried to build entities like this (I renamed Entity class to Entidad)
RelationshipType.java
#Entity
#Table(name = "relationship_type")
public class RelationshipType {
#Id
#GeneratedValue
private Long id;
private String type;
#OneToMany(mappedBy = "relationshipType", fetch = FetchType.EAGER)
private Set<Relationship> relationships = new HashSet<Relationship>();
//Getters and Setters
Relationship.java
#Entity
#Table(name = "relationship")
public class Relationship {
#Id
#ManyToOne
private RelationshipType relationshipType;
#Id
#ManyToOne
private Entidad entity;
//Getters and Setters
Entidad.java
#Entity
#Table(name = "entity")
public class Entidad {
#Id
#GeneratedValue
private Long id;
private String image;
private String foundationNotes;
private String alias;
private Boolean excludeNotifications;
private String notes;
//[...]
#ManyToOne
private Relationship related;
#OneToMany(mappedBy = "entity", fetch = FetchType.EAGER)
private Set<Relationship> relationships = new HashSet<Relationship>();
But when I launch app throws this:
Foreign key (FK_9d8afoh1pv9r59iwjkbcpnud1:entity [])) must have same number of columns as the referenced primary key (relationship [relationshipType_id,entity_id])
At now, I don't know where is the problem and need do this well because I'm using this entities to build the DB schema.

#OneToOne relationship with additional constraint

Suppose, we have two entities, first one:
#Entity
#Table(name = "entitya")
public class EntityA {
#Id
#Column(name = "id")
private Long id;
#Column(name = "name")
private Long name;
#OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private Set<EntityB> childEntities;
}
and the second:
#Entity
#Table(name = "entityb")
public class EntityB {
#Id
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "master")
private Boolean master;
#ManyToOne
#JoinColumn(name = "parent")
private EntityA parent;
}
So far, so good. However underlying database tables and constrains enforce that for any entityA there can be only one EntityB with boolean field master set to true. I can extract it by adding following method to entityA:
public entityB getMasterChild() {
for(entityB ent : childEntities) {
if(ent.isMaster()) {
return ent;
}
}
}
The question is, can I create #OneToOne relationship in EntityA that can express that rule, so that entityA can have additional masterChild member of type entityB?
If I understood you correctly you want to create/define a relationship between two entities based on a value of some entity's property. The think is that relationship between entities is defined on entities count (how many entities can has the other entity) and not on some entity's property value.
However
If you really want to use #OneToOne mapping for masterChild I would recommend creating a separate table/entity for it. Once this is done, you can include this new MasterChild entity into EntityA and annotate it with #OneToOne.
Here is new MasterChild entity
#Entity
public class MasterChild extends EntityB{
#Id
#Column(name = "id")
private Long id;
}
Note that I have removed 'master' from EntityB as it is no longer needed
#Entity
#Table(name = "entityb")
public class EntityB {
#Id
#Column(name = "id")
private Long id;
#Column(name = "name")
private String name;
#ManyToOne
#JoinColumn(name = "parent")
private EntityA parent;
}
And here is modified EntityA
#Entity
#Table(name = "entitya")
public class EntityA {
#Id
#Column(name = "id")
private Long id;
#Column(name = "name")
private Long name;
#OneToOne
private MasterChild master;
#OneToMany(mappedBy = "parent", fetch = FetchType.LAZY)
private Set<EntityB> childEntities;
}

Create and populate child table from Parent table using Hibernate Annotation

I need to create a table EMPLOYEE_REMARK from a table EMPLOYEE.
And need to do it with Annotation Hibernate.
EMPLOYEE
EMP_ID, EMP_FNAME, EMP_LNAME
EMPLOYEE_REMARK
EMP_REMARK_ID, EMP_ID, REMARK
it will be a OnetoOne relationship i.e, for each EMP_ID there will be one REMARK. REMARK could be null.
please help me with the solution...
Can it be done by creating one class from employee and populate the EMPLOYEE_REMARK from it???
Basically here is the way of doing what you want.
Employee
#Entity
#Table(name = "EMPLOYEE")
public class Employee implements Serializable {
#Id
#Column(name = "EMP_ID")
private Long id;
#Column(name = "EMP_FNAME")
private String firstName;
#Column(name = "EMP_LNAME")
private String lastName;
#OneToOne(mappedBy = "employee", cascade = CascadeType.ALL,
orphanRemoval = true)
private EmployeeRemark employeeRemark;
public void setRemark(String remark) {
this.employeeRemark = new EmployeeRemark();
this.employeeRemark.setRemark(remark);
this.employeeRemark.setEmployee(this);
}
public String getRemark() {
return employeeRemark == null ? null : employeeRemark.getRemark();
}
//getters and setters
}
Employee Remark
#Entity
#Table(name = "EMPLOYEE_REMARK")
public class EmployeeRemark implements Serializable {
#Id
#Column(name = "EMP_REMARK_ID")
private Long id;
#OneToOne
#JoinColumn(name = "EMP_ID")
private Employee employee;
#Column(name = "REMARK")
private String remark;
//getters and setters
}
When saving employee, just call save on employee. EmployeeRemark will cascade to all operations and will be removed along with employee or if it become an orphan in other way.

Categories

Resources