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.
Related
What's the correct way to create bidirectional 1to1 mapping using Embeddable annotation? This one throws error
"EmpId has no persistent id property: Emp.id"
#Entity
public class Per implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "per_id")
private Long id;
#OneToOne
#JoinColumn(name = "per_id", referencedColumnName = "emp_id")
private Emp emp;
}
#Embeddable
public class EmpId implements Serializable {
private static final long serialVersionUID = 1L;
#OneToOne(mappedBy = "emp")
private Per per;
}
#Entity
public class Emp implements Serializable {
#EmbeddedId
private EmpId id;
}
I'd like to operate entities like
per.getEmp();
emp.getId().getPer();
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.
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;
Ok so I have an Entity School.
#Entity
public class School implements Serializable
{
private static final long serialVersionUID = -854333301529125138L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long ID;
private String Type;
private String Name;
private String City;
private String Country;
#OneToOne(cascade = CascadeType.PERSIST,fetch=FetchType.LAZY)
private Info information;
#OneToMany(cascade = CascadeType.PERSIST, mappedBy="school",fetch=FetchType.LAZY)
private List<Contact> Contacts;
#OneToMany(cascade = CascadeType.PERSIST, mappedBy="school",fetch=FetchType.LAZY)
private List<Student> students= new ArrayList<Student>();
// more fields and getters and setters.
The Student Class contains lots of student information, and the student transcripts and is as follows
#Entity
public class Student implements Serializable
{
private static final long serialVersionUID = 5426530769458891752L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Key ID;
#ManyToOne
private School school;
private long SID;
private final long TSTAMP;
private String FName;
private String LName;
private String Email;
private String SchoolName;
#OneToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)
private StudentInfo studentInf = new StudentInfo ();
#OneToOne(cascade = CascadeType.ALL,fetch=FetchType.LAZY)
private Transcript transcript;
// more fields and getters and setters.
the Transcript Class in the Student Class is as follows
#Entity
public class Transcript
{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Key ID;
#OneToOne(cascade = CascadeType.ALL, mappedBy="transcript",fetch=FetchType.LAZY)
private Student student;
#Embedded
private Course1 c1;
#Embedded
private Course2 c2;
#Embedded
private Course3 c3;
//... ect
public Transcript()
{
this.c1= new Course1();
this.c2= new Course2();
this.c3= new Course3();
// ... ect
}
// more fields and getters and setters.
and finally here is a sample course class
#Embeddable
public class Course1 implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -7643055124732162110L;
private final String CourseTitle = "Course 1 Title";
private boolean MileStone1 = false;
private boolean MileStone2 = false;
// ... ect ... getters and setters
}
All the classes Enhance without a problem and the server runs, but as soon as a Student Instance is created, it results in a total catastrophe in GAE dev server and I have tried alot of possible options with the same error message:
"java.lang.IllegalArgumentException: org.datanucleus.exceptions.NucleusUserException: You have a field db.Entity.student.Student.transcript that has type db.Entity.Courses.Transcript but this type has no known metadata. Your mapping is incorrect"
I would very very much appreciate an explanation on why this is happening and how to fix it while keeping the logical relations
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.