How to retrieve list of objects by list of fields - spring-data-jpa

Table user has following schema
id integer PRIMARY KEY,
name varchar(120) NOT NULL,
ssn integer NOT NULL
Spring Data JPA provides following in CrudRepository interface to retrieve one user based on id
Optional<User> findById(Integer id);
But I want to retrieve all User.names,given an list of id's (assume list has no repetions); how can I retrieve their names. I know I can loop the above findById, but that is not practical when table size is very big

Use findByIdIn for find by the list of ids and get the user list.
List<User> findByIdIn(List<Integer > ids);
And for only get names of users of given ids
#Query(value = "SELECT c.name FROM User c WHERE id IN (?1)")
public List<String> findAllNames(List<Integer> ids);

Related

Select Map<Integer, Integer> using mybatis

I want to select Map for each record. Result class looks like
public class Mapping {
private String name;
private Map<Integer, Integer>;
}
SQL table has only three columns namely name, id, partner_id.
How can I create Map of Id to Partner Id for each name using mybatis?
you can use sqlSession.selectForMap, and give mybatis the column which will be processed as the key of map , such as name. then it will return
Map<String,Map<String,Object>>
as a result, but the value is Map, key is the column name, you need to transform it .

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']
}
}

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);

Is there a way to update a database field based on a list?

Using JPA, I have a list of entries from my database :
User(id, firstname, lastname, email)
That I get by doing:
List<User> users = User.find("lastname = ?", "smith");
And I'd like to update all in one request, by doing something like this :
"UPDATE USER SET email = null IN :list"
and then set the parameter "list" to users
Is it possible? if so, how?
Thanks for your help :)
Well, you could embed the query that you used to obtain list in the where clause of the update.
UPDATE User a SET a.email = null
WHERE user IN (SELECT b FROM User b WHERE lastName = :?)
By doing this you'd be doing the query to search the list and the update in single update query.
How do you like that? Do you think this could work?
-EDIT-
Since you want to use the original list of items instead of a list just retrieved from the database, you can still ensure you build the original list like this
UPDATE User a SET a.email = null
WHERE user IN (SELECT b FROM User b WHERE lastName IN(:originalList))
Then when you invoke it, you can do something like this:
Collection<String> originalList = Arrays.asList("Kenobi", "Skywalker", "Windu");
query.setParameter("originalList", originalList);
By this, you can still ensure the query will only contain items in your original list and not any possible new item from the database, provided that that last name is a candidate key in the database, otherwise I would recommend that you use the ID for the subquery instend of the last name.
if you have jpa+hibernate you can use entityManager.createQuery() for creating hql query
like that:
String hql = "UPDATE Supplier SET name = :newName WHERE name IN :name";
entityManager.createQuery(hql);