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.
Related
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.
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.
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;
}
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;
Hi i am learning about #ManyToMany relationship mapping using JPA.
I more or less understand how it works, but i have a doubt. Let me show you first this code where i do some mapping:
#Entity
public class EntityE implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long eId;
#ManyToMany
#JoinTable(joinColumns =
#JoinColumn(name = "eId"), inverseJoinColumns =
#JoinColumn(name = "fId"))
private Collection<EntityF> entityFs;
//...
}
Also see this other entity:
#Entity
public class EntityF implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long fId;
private Collection<EntityE> entityEs;
//...
}
This is what i get in the database:
My doubts are:
-I want to create a #ManyToMany relationship where EntityE is the owner of the relationship, is this approach correct?
-I want the relationship to be unidirectional, so it is supposed to create just one mediator table called EntityB_EntityF. But for some reason it creates also a second table called EntityF_EntityE. I dont understand why is that?,Is that normal? and if not how should i fix it?
Ok i just got the answer after doing some little experiment.I think it is correct, it now works as i spected.
What i did was, add a name for the relationship, because for some strange reason if you don't specify the name it creates a bidirectional relationship.
See this code fixed it:
#Entity
public class EntityE implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long eId;
#ManyToMany
#JoinTable(name="entitye_entityf",joinColumns =
#JoinColumn(name = "eId"), inverseJoinColumns =
#JoinColumn(name = "fId"))
private Collection<EntityF> entityFs;
Here is the other entity.
#Entity
public class EntityF implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long fId;
#ManyToMany
#JoinTable(name="entitye_entityf",joinColumns =
#JoinColumn(name = "fId"), inverseJoinColumns =
#JoinColumn(name = "eId"))
private Collection<EntityE> entityEs;
So as you can see from the image, managed to solve my doubts. I hope this answer can be useful for someone else as well.