JPA #OneToMany not fetching the childern - jpa

Following is the table structure:
desc customer_survey
Name Null Type
----------- -------- ------------
SURVEYID NOT NULL VARCHAR2(10)
CUSTNO NOT NULL VARCHAR2(10)
SRNO NUMBER(10)
AVGRATINGS NUMBER(5,2)
COMMENTS VARCHAR2(50)
SENTON DATE
RESPONDEDON DATE
desc Survey_response
Name Null Type
---------------- -------- ------------
SURVEYRESPONSEID NOT NULL NUMBER(10)
RATINGS NOT NULL NUMBER(2)
QNO NOT NULL VARCHAR2(10)
SURVEYID NOT NULL VARCHAR2(10)
Java classes:
public class CustomerSurvey implements Serializable {
#OneToMany(fetch=FetchType.EAGER, mappedBy="customerSurvey",
cascade=CascadeType.ALL)
private Set<SurveyResponse> responses;
......
public class SurveyResponse {
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="SURVEYID", referencedColumnName="surveyId")
private CustomerSurvey customerSurvey;
......
Client code:
List<CustomerSurvey> surveys = workService.getSurveysByCustomer("testCNo2");
System.out.println("surveys size = " + surveys.size());
for(CustomerSurvey survey: surveys) {
System.out.println("getting responses from the survey object now..");
Set<SurveyResponse> responses = survey.getResponses();
System.out.println("responses size= .." + responses.size());
}
console shows:
surveys size = 1
getting responses from the survey object now..
responses size= ..0
whereas there are 7 responses in the DB for the selected survey.

Enable logging and look if the SQL is correct.
It is hard to tell from your incomplete code, but in general a OneToMany should not use a JoinColumn it should use a mappedBy, and the join column in the ManyToOne should reference the Id of the object.
Also ensure you are setting both sides of the relationship when you insert your objects.

Another option is to populate the relationship with a jpql fetch query:
"select survey from Surveys survey join fetch survey.responses"
I had the same problem and still can't find out what is going wrong. In my case the parent entity was loaded by a jpql query, and so extending this provided a workaround

this link helped.
I set the collection back to lazy. And
Inside persistence class, within transaction after getting the resultset, I am now calling getResponses as:
List<CustomerSurvey> surveys = query.getResultList();
for (CustomerSurvey survey : surveys) {
Set<SurveyResponse> responses = survey.getResponses();
}
that populates the responses.

Related

How to create association one to many and many to one between two entities in gorm?

I'm new in Grails. I have a problem with generation association many to one and one to many between two tables. I'm using postgresql database.
Employee.groovy
class Employee {
String firstName
String lastName
int hoursLimit
Contact contact
Account account
Unit unit
char isBoss
static hasMany = [positionTypes:PositionType, employeePlans: EmployeePlan]
}
EmployeePlan.groovy
class EmployeePlan {
AcademicYear academicYear
HourType hourType
int hours
float weightOfSubject
Employee employee
static belongsTo = [SubjectPlan]
}
I'd like to have access from employee to list of employeePlans and access from EmployeePlan to Employee instance. Unfortunately GORM generates only two tables Employee and EmployeePlan with employee_id. I don't have third table which should have two columns employee_id and employee_plan_id. Could you help me ?
I think your setup is correct, as you write from Employee class you can access to a collection of EmployeePlan (take care, that if you don't explicitly define EmployeePlan like a List, it will be a Set by default) and from EmployeePlan you can access Employee.
If you need List, you can define it like that:
class Employee {
String firstName
String lastName
int hoursLimit
Contact contact
Account account
Unit unit
char isBoss
//explicitly define List
List<EmployeePlan> employeePlans
static hasMany = [positionTypes:PositionType, employeePlans: EmployeePlan]
}
But back to your question. You'd like to have join table between Employee and employeePlan, but why? Its not necessary, since you have bidirectional mapping with sets (unordered), grails will not create a join table. Can you explain why do you need it? In grails the references will be auto-populated, so I don't see any issue here.
If need to preserve order of employeePlans, then define it as List, shown above, and grails will create a join table with corresponding indexes.
have you read the ref-doc? it gives you the answer immediately:
class Person {
String firstName
static hasMany = [addresses: Address]
static mapping = {
table 'people'
firstName column: 'First_Name'
addresses joinTable: [name: 'Person_Addresses',
key: 'Person_Id',
column: 'Address_Id']
}
}

How to configure default Where clause in Hibernate Entity (POJO) HQL

I have set of entity (POJO) classes, Each entity class will have one property stopDate , which is type of Date.
#Entity
#Table(name="ORG")
public class Organization extends PersistentObjImpl {
private Long odbid; //ODBID NUMBER(11) i.e. Primary Key
private String actionFeedReqInd;
private String alternateName;
private Date stopDate; //STOP_DATE NOT NULL DATE
#Temporal(TemporalType.DATE)
#Column(name="STOP_DATE", nullable=false)
public Date getStopDate() {
return stopDate;
}
public void setStopDate(Date stopDate) {
this.stopDate = stopDate;
}
//setter and getter methods for corresponding columns i.e. properties
}
in Organization Database table, if any row's stop_date column value is less than current date(sysdate) , we should not fetch those rows using Hibernate.
Ex: Org data base table.
ODBID Column1 Column2 stop_date
1 - - 2015-02-13
2 - - 2010-04-23
3 - - 2009-03-13
Here is the SQL statement and Output ,which I am expecting.
SELECT ODBID, , from ORG WHERE stop_date>sysdate ;
ODBID Column1 Column2 stop_date
1 - - 2015-02-13
Like this , I have so many tables, which has stop_date as column, from any one of the table, if the stop_date < sysdate, i don't want to retrieve those records ..
I am not interested to write stop_date>sysdate condition in each SQL/HQL select query. Is there any way I can configure this condition once, and use in all the Entity (POJO ) classes.
Please provide me a generic way.

Using Inner joins in Entity Framework on multiple tables?

I have a student table in my database with columns Id, Name, DepartmentId, CollegeId, CityId etc and a Department table, College table to map to the DepartmentId, CollegeId in the Student table.
Now I want to pass CityId and retrieve Id, Name, DepartmentName, CollegeName with help of the corresponding tables using inner join based on the CityId.
I'm implementing a method FindAll() which takes in CityId as the input parameter and retrieves data based on CityId
public IEnumerable<StudentRegionEntity> FindAll(int CityId)
{
var totalStudents = new List<StudentRegionEntity>();
foreach(var entity in this.Dbcontext.Students)
{
}
}
In the foreach loop I want to bind the list of students with Id, Name, Department, College fields, how can I use joins and implement the functionality for FindAll()?
var studentEntities = this.Dbcontext.Students
.Include("StudentList").Where(s => s.cityId == CityId).ToList()
this will give the list of all the StudentEntity entities with StudentRegionEntity attached, using one join query to the database.

Entity Framework Return Parent along with child entity as Ieunmerable List

I am new to Entity Framework and had a question i have been stuck on for a while. I have a repository in my DAL to access the data its returning IEnumerable lists for functions defined there. There are two tables involved here table Company and thier Customer_orders please see below for details. I need to return an Ienumerable list for Customer Orders ...which also includes the Customer name. I am able to return everything back for the customer order table but cant get the Customer name from the related table. Is it because I am returning a list of Ienumerable CustomerOrder type? If anyone can provide some help by showing the right code it would be greatly appreciated. Once again I am trying to bind to a grid pulling from the CustomerOrders table but need to also display CustomerName from Customers table.
Table1 (Customers)
company_id
customer_id
customerName
customerAddress
Table 2 (CustomerOrders)
customer_id
product_id
productName
productDesc
This is what I have so far this doesnt pull up any customer Names but pulls the CustomerOrders information
public IEnumerable<CustomerOrders> GetCustomerOrders(int company_id)
{
return context.Customers.Where(c => c.company_id == company_id).First().CustomerOrders.ToList().OrderBy(p => p.ProductName);
}
How about:
return context.CustomerOrders
.Include(o => o.Customer)
.Where(o => o.customer_id == customer_id);

Entity Framework: perform a query on a linking table / many to many relationship

I am trying to perform a query using linq to entities to that an entity/table doesn't contain the same values before I update it.
The structure of the database is as follows:
Users User_IPAddresses IPAddresses
----- ---------------- -----------
UserID >------ UserID ------< IPAddressID
User IPAddressID Address
So, the structure of the entity object is as follows
UserSet IPAddressSet
------- >-----< ------------
User IPAddress
All the ID fields are Primary Keys, so the link table (User_IPAddresses) must contain unique rows.
The problem I am having is that I can't get my head around how to check the entities so that I don't violate the unique row constraint on the User_IPAddresses table before I update it.
Any EF gurus out there that can help me?
//returns true if pair exists
public bool CheckIfUserIPPairExists(int ipID, int userID)
{
bool exists
= db.UserSet.Any(user=>user.UserID==userID
&& user.IPAddress.Any(ip=>ip.IPAddressID == ipID));
return exists;
}