annotations on entites with same superclass - java

Consider two entites with the same superclass
#Entity
public class EntityA extends MyEntity {
private static final long serialVersionUID = 1L;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "int_calc_id")
private Calculation calculation;
}
#Entity
public class EntityB extends MyEntity {
private static final long serialVersionUID = 1L;
#Column(name = "calculation_id")
private Integer calculationId;
}
Calculation is an entity corresponding to the calculationId. So my first refactoring would be to use the class in both entities. My question is: Can I shift the calculation to MyEntity?

public class EntityA extends MyEntity {
private static final long serialVersionUID = 1L;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "int_calc_id")
private Calculation calculation;
}
public class EntityB extends MyEntity {
private static final long serialVersionUID = 1L;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "int_calc_id")
private Calculation calculation;
}

Related

ReferencedColumnNames not mapped to a single property using composite key

Well,
after reading almost every post I decided to post my question because I'm not able to fix it.
Class A has a Primary Key (4 fields)
Class B has a Primary Key (2 fields)
#Entity
public class ClassA implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private ClassAPK id;
//bi-directional many-to-one association to ClassB
#OneToMany(mappedBy="classA")
private Set<ClassB> classB;
Class B
#Entity
public class ClassB implements Serializable {
private static final long serialVersionUID = 1L;
#AttributeOverrides({
#AttributeOverride(name = "id", column = #Column(name = "ID")),
#AttributeOverride(name = "cod", column = #Column(name = "cod")),
#AttributeOverride(name = "year", column = #Column(name = "year")),
#AttributeOverride(name = "month", column = #Column(name = "month")) })
#EmbeddedId
private ClassBPK id;
// bi-directional many-to-one association to ClassA
#ManyToOne
#JoinColumns({
#JoinColumn(name = "id", referencedColumnName="ID")
})
private ClassA classA;
#Embeddable
public class ClassBPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#Column(name="ID")
private long id;
private int day;
public ClassBPK() {
}
Any suggestions?
Thanks

JPA cascade not inserting foreign key

I have 2 entity classes - Order and OrderDetail. Below are code snippets of these two classes.
#Entity
#Table(name="orders")
#IdClass(OrderPK.class)
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Id
private String customerEmail;
#Column(name="advance_order_time")
private Date advanceOrderTime;
#Column(name="amount")
private float amount;
#OneToMany(mappedBy = "order", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
private Set<OrderDetail> orderDetailList;
public void addOrderDetail(OrderDetail orderDetail) {
if (orderDetail != null) {
if (orderDetailList == null) {`enter code here`
orderDetailList = new HashSet<OrderDetail>();
}
orderDetailList.add(orderDetail);
orderDetail.setOrder(this);
}
}
}
#Entity
#Table(name="order_details")
public class OrderDetail implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="item_code")
private String itemCode;
#ManyToOne
#MapsId("id")
private Order order;
}
public class OrderPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
private int id;
#Column(name="customer_email")
private String customerEmail;
}
Order object and the collection of OrderDetail objects are inserted successfully in the database but the order_id column of OrderDetail in null. Below is the code snippet.
entityManager.persist(kfcOrder);
order table has a composite key id and customer_email. This id is foreign key of table order_details of column order_id.
Please suggest a work around so that while persisting order object in database order_id of order_details table also gets saved.
try this..
#ManyToOne(optional = false)
#JoinColumns({
#JoinColumn(name = "ORDER_ID",referencedColumnName = "id"),
#JoinColumn(name = "EMAIL",referencedColumnName = "customerEmail")
})
#MapsId("id")
private Order order;
optional = false will ensure that no child can exist if parent doesn't exist.

OneToMany Hibernate Failed To Save

I have problem with OneToMany saving problem using hibernate.
#Entity
#Table(name="lecturer")
public class LecturerEntity extends BaseEntity implements Serializable{
private static final long serialVersionUID = 446089492592652000L;
#Id
#Column(name="id")
#GeneratedValue
private int id;
#Column(name="lecturer_name")
private String lecturerName;
#ManyToOne
#JoinColumn(name="department_id")
private DepartmentEntity department;
}
#Entity
#Table(name="Department")
public class DepartmentEntity extends BaseEntity implements Serializable {
private static final long serialVersionUID = -6221599323765325196L;
#Id
#Column(name="id")
#GeneratedValue
private int id;
#Column(name="department_name")
private String departmentName;
#OneToMany(cascade = CascadeType.ALL, mappedBy="department")
private List<LecturerEntity> lecturers;
}
/*
* One to Many Bidirectional DepartmentEntity and LecturerEntity
*/
departmentRepository = ctx.getBean(DepartmentRepository.class);
lecturerRepository = ctx.getBean(LecturerRepository.class);
department = new DepartmentEntity("Department");
List<LecturerEntity> lecturers = new ArrayList();
lecturers.add(new LecturerEntity("Lecturer 1"));
lecturers.add(new LecturerEntity("Lecturer 2"));
department.setDepartments(lecturers);
departmentRepository.saveDepartment(department);
I got this in my table
Result
Why is department_id in Lecturer table null?
please help, I can't spot the problem.
Thanks.

Entity without Primary Key ID

Hi I want to create an Entity which doesn't have an ID.
#Entity
#Table(name="USER_PROD_LIC_TYPE_ALL")
public class UserProdLicTypeAll {
#EmbeddedId
private UserProdLicTypeAllPK id;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="LICENSE_TYPE_ID")
private LicenseType licType;
....
}
since it doesn't have primary key i created Embeddable class as below:
#Embeddable
public class UserProdLicTypeAllPK {
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="USER_ID")
private User user;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="LICENSE_TYPE_ID")
private LicenseType licType;
...
}
The combination of these two fields returns a unique value.
But it doesn't work. I get
org.springframework.beans.factory.UnsatisfiedDependencyException: exception.
Do i need to have references in User and LicenseType entities for both UserProdLicTypeAll and UserProdLicTypeAllPK? I have tried that also but still it doesn't work.
This is my private hell. I'm not sure what the best way to solve it properly.
My best solution is:
#Entity
#Table(name = TableName.AREA_USER)
#IdClass(UserAreaPK.class)
public class UserArea implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = UserAreaPK.C_AREA_ID)
private Long areaId;
#Id
#Column(name = UserAreaPK.C_USER_ID)
private String userId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = UserAreaPK.C_AREA_ID, insertable = false, updatable = false)
private Area area;
And
/**
* Primary key for the relationship User-Area
*/
public class UserAreaPK implements Serializable {
protected static final String C_AREA_ID = "area_id";
protected static final String C_USER_ID = "user_id";
private static final long serialVersionUID = 1L;
#Id
#Column(name = C_AREA_ID)
private Long areaId;
#Id
#Column(name = C_USER_ID)
private String userId;

createAlias/createCriteria hibernate INNER_JOIN

I am having two tables Parent and Child. The query I want to use in Hibernate Criteria
SELECT tcr.*
FROM case_reminders tcr
INNER JOIN case_reminder_opr tco ON tcr.case_id = tco.case_id
WHERE tcr.case_status = 'OPN'
AND tco.operator_id = 111;
I have written the criteria as
Criteria ctr = getSession().createCriteria(CaseReminderOpr.class).add(Restrictions.eq("pk.oprOperatorId", operatorId));
ctr.createCriteria("pk.crmCaseId", "CR", Criteria.INNER_JOIN).add(Restrictions.eq("CR.caseStatus", STATUS.OPEN.getValue()));
List<CaseReminderOpr> oprList = ctr.list();
tried with createAlias as well but I am getting error as
ORA-00904: "CR1_"."CASE_STATUS": invalid identifier
Classes of CaseReminders(Parent) and CaseReminderOpr(Child) as follows.
#Entity
#Table(name = "CASE_REMINDERS")
public class CaseReminders implements Serializable {
#Id
#Column(name = "CASE_ID")
private Long caseId;
#Column(name = "CASE_STATUS")
private String caseStatus;
}
#Entity
#Table(name="CASE_REMINDER_OPR")
public class CaseReminderOpr implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private CaseReminderOprPK pk;
}
#Embeddable
public class CaseReminderOprPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
#ManyToOne
#JoinColumn(name = "CASE_ID")
private CaseReminders crmCaseId;
#Column(name="OPERATOR_ID")
private Long operatorId;
}
Please help me with the inner_join query, appreciate your help again.
The change would be as below then it works. I have realized this later.
Make the Joincolumn as insertable=false,updatable=false in main entity class.
#Entity
#Table(name="CASE_REMINDER_OPR")
public class CaseReminderOpr implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
private CaseReminderOprPK pk;
#ManyToOne
#JoinColumn(name = "CASE_ID", insertable=false, updatable=false)
private CaseReminders caseRem;
}
Now the query should work as expected.
Criteria ctr = getSession().createCriteria(CaseReminderOpr.class, "CRO").add(Restrictions.eq("pk.oprOperatorId", operatorId));
ctr.createCriteria("CRO.caseRem", "CR", Criteria.INNER_JOIN).add(Restrictions.eq("CR.caseStatus", STATUS.OPEN.getValue()));
List<CaseReminderOpr> oprList = ctr.list();
Hopefully I am clear in explaining.

Categories