JPA cascade not inserting foreign key - java

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.

Related

Two model java mapped with one to many mapping but data not mapped with required colomns

I have used one to many relationship between two models with join colomn(crnumber) but crnumber colomn data updated with id colomn data from Parent table . Two mapping models pasted in below
#Entity
#Table(name = "CREFFORTSTABLE")
public class CREffortDetails{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String crNumber;
private String description;
private int totalPlannedHours;
private int totalActualHours;
#OneToMany ( mappedBy = "cREffortDetails", cascade = CascadeType.ALL )
private List<TaskData> taskData = new ArrayList<TaskData>();
#Entity
#Table(name = "CRTASKDATA")
public class TaskData {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
//private String crNumber;
private String task;
private String weekNumber;
private String plannedHours;
private String actualHours;
#Transient
private Integer remove;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "crNumber", nullable = false)
private CREffortDetails cREffortDetails;
Out put should be
CREFFORTSTABLE
id crnumber description totalplannedhours totalactualhours
1 CH001234 0 10 10
CRTASKDATA
id task weeknumber plannedhours actualhours crnumber
1 test w1 2 2 CH001234

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

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;

How to use a child association property as a Map key in JPA parent entity

I'm having two entities Car and CarDescription where CarDescription is depending on another foreign key from the table Language.
What I' trying to accomplish is to have a HashMap in Car such that whenever I'm having a Car entity-object I am able to access all descriptions from the language id.
Entity Car.java
#Entity
#Table(name = "Car")
public class Car extends AbstractTimestampEntity implements Serializable {
private static final long serialVersionUID = -5041816842632017838L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "ID", unique = true, nullable = false)
private Long id;
#OneToMany(mappedBy="car")
#MapKeyColumn(name = "language_ID")
// #MapKey(name = "language") // does not work either
private Map<Long, CarDescription> carDescription = new HashMap<>(0);
}
Entity CarDescription.java
#Entity
#Table( name="car_description",
uniqueConstraints = {
#UniqueConstraint(columnNames={"language_id", "name"})
}
)
public class CarDescription extends AbstractTimestampEntity implements Serializable {
private static final long serialVersionUID = 2840651722666001938L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "ID", unique = true, nullable = false)
private Long id;
#NotNull
#ManyToOne
private Car car;
#NotNull
#OneToOne
private Language language;
// ..
}
Entity Language.java
#Entity
public class Language implements Serializable {
private static final long serialVersionUID = 3968717758435500381L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID")
private Long id;
// ..
}
The problem I am having is that the mapping gives me a map from each CarDescription.id to CarDescription.
How can I accomplish a correct mapping?
In CarDescription you need to add the languageId property:
#Column(name = "language_id", insertable = false, updatable = false)
private Long languageId;
#NotNull
#OneToOne
#JoinColumn(name = "language_id")
private Language language;
public void setLanguage(Language language) {
this.languageId = language.getId();
this.language = language;
}
Then you can use it in the Car entity like this:
#OneToMany(mappedBy="car")
#MapKey(name = "languageId")
private Map<Long, CarDescription> carDescription = new HashMap<>(0);

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