How to get the other details when I click next button? - java

//This is my controller
#RequestMapping("/getList")
public ModelAndView getList(#RequestParam(value="page",required=false) Integer page,Model model,#RequestParam(value="page_size",required=false) Integer page_size){
page=0;
page_size=4;
List<Employee> empList = empService.getEmpList1(page,page_size);
Employee emp=new Employee();
model.addAttribute("employee", emp);
return new ModelAndView("empList", "empList", empList);
}
//This is my Sql Query........
select * from EmpDetails LIMIT +page+","+page_size;
//This is my jsp.......for next button.....
Next:
By using this code I am getting the records(0-4) of employee in one page.
My question is when I click on next button the records(4-8) of employees must be displayed in other page. Can you please tell me how to write the code?

Try this code
#RequestMapping("/getList")
public String getList(#RequestParam(value = "page", required = false) Integer page, Model model,
#RequestParam(value = "page_size", required = false) Integer page_size) {
if (page == null) {
page = 0;
}
if (page_size == null) {
page_size = 4;
}
List<Employee> empList = empService.getEmpList1(page, page_size);
Employee emp = new Employee();
model.addAttribute("employee", emp);
model.addAttribute("empList", empList);
model.addAttribute("page", page);
model.addAttribute("page_size", page_size);
return "empList";
}
//This for next button in jsp..... Try and let me know if this link work?
Next:
//This is my Sql Query........
recordStart = page * page_size;
select * from EmpDetails LIMIT +recordStart+","+page_size;

You should not assign strict values to page and page_size variables in your method. Instead of this you should get values from parameters passed to method.
#RequestMapping("/getList")
public ModelAndView getList(#RequestParam(value="page",required=false) Integer page,Model model,#RequestParam(value="page_size",required=false) Integer page_size){
List<Employee> empList = empService.getEmpList1(page,page_size);
Employee emp=new Employee();
model.addAttribute("employee", emp);
return new ModelAndView("empList", "empList", empList);
}
Of course if your page and page_size is optional then you have to check if values are passed. If not then you have to assign some default values.

Related

Why am I getting multiple duplicate criteria results for an ID if it has a one-to-many mapped table with multiple data

I have a parent Entity called CustomerDetailsEntity. It has following one to many mapping to another Entity IBPSDiscrepancyFieldsEntity.
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "Customer_discrepancy_fk", referencedColumnName = "customer_detail_id")
private Set<IBPSDiscrepancyFieldsEntity> ibpsDiscrepancyFieldsEntity;
Now, say for id=123, in IBPSDiscrepancyFieldsEntity Table, I have 4 rows of data.
Now when I hit criteria search on CustomerDetailsEntity I am getting 4 results with same data instead of one. This is how my search criteria is written:
public Map<String, Object> search(Long slrId, String param, String ibpsStatus, Pageable pageable) {
Criteria criteria = getSession().createCriteria(CustomerDetailsEntity.class);
criteria.add(Restrictions.eq("slrDtlId.sellerDtlId", slrId));
criteria.addOrder(Order.desc("modifiedOn"));
if (param != null && !param.isEmpty()) {
Criterion fName = Restrictions.like("customerFirstName", param+"%");
Criterion lName = Restrictions.like("customerLastName", param+"%");
Criterion appNo = Restrictions.like("loanAppNumber", "%"+param+"%");
Disjunction orExp = Restrictions.or(fName, lName, appNo);
criteria.add(orExp);
}
if (ibpsStatus != null && !ibpsStatus.isEmpty()) {
if (ibpsStatus.equalsIgnoreCase(Constant.IBPS_DISCREPANT)) {
criteria.add(Restrictions.eq("ibpsStatus", IBPSStatus.IBPS_DISCREPANT));
} else if (ibpsStatus.equalsIgnoreCase(Constant.IBPS_RESOLVED)) {
criteria.add(Restrictions.eq("ibpsStatus", IBPSStatus.IBPS_RESOLVED));
}
} else {
Criterion discrepant = Restrictions.eq("ibpsStatus", IBPSStatus.IBPS_DISCREPANT);
Criterion resolved = Restrictions.eq("ibpsStatus", IBPSStatus.IBPS_RESOLVED);
LogicalExpression orExp = Restrictions.or(discrepant, resolved);
criteria.add(orExp);
}
criteria.setFirstResult(pageable.getPageSize() * pageable.getPageNumber());
criteria.setMaxResults(pageable.getPageSize());
List<CustomerDetailsEntity> result = (List<CustomerDetailsEntity>) criteria.list();
Map<String,Object> countResultMap = new HashMap<>(2);
countResultMap.put(Constant.QUERY_RESULT, result);
logger.info("##### checking here");
logger.info("--->"+result.size());
criteria.setFirstResult(0);
Long count = (Long) criteria.setProjection(Projections.rowCount()).uniqueResult();
logger.info("Total Count : "+count);
countResultMap.put(Constant.TOTAL_COUNT, count);
return countResultMap;
}
How do I get only 1 result of CustomerDetailsEntity id=123 when I search, instead of 4 duplicate values. In the logs, result.size() shows as 4. Is the Issue with my mapping or criteria method? Please help.

JDBC resultset into java POJO with list member

I have two query and resultsets, in the below code I want to showcase that for a particular userGroupCode I have certain userPreference and employee associated with it. I have written the code below code to display the userGroupCode object:
String query1= "SELECT ug.userGroupCode, ug.userGroupDesc, up.userPreference"
+ "FROM dbo.UserGroup_link ug INNER JOIN dbo.UserPreference up ON ug.userGroupCode = up.userGroupCode";
userGroupCode
userGroupDesc
userPreference
A100
Finance
Mumbai
A100
Finance
Bangalore
A200
Supply Chain
Chennai
A201
Marketing
Delhi
A201
Marketing
Kolkata
A300
Health
Indore
String query2= "SELECT ug.userGroupCode, ug.userGroupDesc, emp.employee_id,emp.name,emp.role"
+ "FROM dbo.UserGroup ug INNER JOIN dbo.employee emp ON ug.userGroupCode = emp.userGroupCode";
userGroupCode
userGroupDesc
employee_id
name
role
A100
Finance
101
Foo1
Developer
A100
Finance
101
Foo1
Team Lead
A200
Supply Chain
091
Test1
Manager
A201
Marketing
591
User1
Analyst
A201
Marketing
1001
Boo1
Scrum Master
A300
Health
1001
Boo1
Developer
I have class UserGroupMapping like:
public class UserGroupMapping {
private String userGroupCode;
private String userGroupCode;
private List<String> userPreference;
private List<Employee> emp;
//getter and setter
}
Another class for Employee is:
public class Employee {
private String employee_id;
private String name;
private List<String> role;
//getter and setter
}
In my stored procedure class I am calling these queries with the help of jdbcTemplate.query();
String userCode = null;
List<String> userPreferenceList = new ArrayList<>();
List<UserGroupMapping> userGroupMappingList = new ArrayList<>();
List<UserGroupMapping> userGroupMappingList1 = new ArrayList<>();
UserGroupMapping userGroupMapping = new UserGroupMapping();
List<Employee> employeeList = new ArrayList<>();
Employee emp = new Employee();
UserGroupMapping userGroupMapping1 = new UserGroupMapping();
jdbcTemplate.query(query1, (rs)->{
String user_group_code = rs.getString("userGroupCode");
String user_group_desc = rs.getString("userGroupDesc");
String user_preference = rs.getString("userPreference");
if(userCode == null){
userGroupMapping.setUserGroupCode(user_group_code);
userGroupMapping.setUserGroupDesc(user_group_desc);
userPreferenceList.add(userPreference);
userCode = user_group_code;
} else if (userCode.equals(user_group_code)) {
userPreferenceList.add(userPreference);
} else {
userGroupMapping.setUserPreference(userPreferenceList);
userGroupMappingList.add(userGroupMapping);
userPreferenceList = new ArrayList<>();
userGroupMapping = new userGroupMapping();
userGroupMapping.setUserGroupCode(user_group_code);
userGroupMapping.setUserGroupDesc(user_group_desc);
userPreferenceList.add(userPreference);
userCode = user_group_code;
}});
userCode = null;
userGroupMapping.setUserPreference(userPreferenceList);
userGroupMappingList.add(userGroupMapping);
jdbcTemplate.query(query2, (rs)->{
String user_group_code = rs.getString("userGroupCode");
String user_group_desc = rs.getString("userGroupDesc");
String emp_id = rs.getString("employee_id");
String name = rs.getString("name");
if(userCode == null){
userGroupMapping1.setUserGroupCode(user_group_code);
userGroupMapping1.setUserGroupDesc(user_group_desc);
emp.setId(employeeId);
emp.setName(name);
employeeList.add(emp);
userCode = user_group_code;
} else if (userCode.equals(user_group_code)) {
Employee emp = new Employee();
emp.setId(employeeId);
emp.setName(name);
employeeList.add(emp);
} else {
userGroupMapping1.setEmployee(employeeList);
userGroupMappingList1.add(userGroupMapping1);
employeeList = new ArrayList<>();
userGroupMapping1 = new userGroupMapping();
Employee emp = new Employee();
userGroupMapping1.setUserGroupCode(user_group_code);
userGroupMapping1.setUserGroupDesc(user_group_desc);
emp.setId(employeeId);
emp.setName(name);
employeeList.add(emp);
userCode = user_group_code;
}});
userGroupMapping1.setEmployee(employeeList);
userGroupMappingList1.add(userGroupMapping1);
List<UserGroupMapping> ugList = Stream.concat(userGroupMappingList.stream, userGroupMappingList1.stream).distinct().collect(Collectors.toList())
return ugList;
The problem is that I want my output to be like :
[
{
"userGroupCode" : "A100",
"userGroupDesc" : "Finance",
"userPreference": ["Mumbai","Bangalore"],
"Employee" : [
"employee_id" : "101",
"name" : "Foo1",
"role" : ["Developer","Team Lead"]
]
}
]
After merging the two list I am getting the below output:
[
{
"userGroupCode" : "A100",
"userGroupDesc" : "Finance",
"userPreference": ["Mumbai","Bangalore"],
"Employee" : []
},
{
"userGroupCode" : "A100",
"userGroupDesc" : "Finance",
"userPreference": [],
"Employee" : [
"employee_id" : "101",
"name" : "Foo1",
"role" : []
]
}
]
Could anyone please help me with few things:
How could I embed the role into the Employee object.
How can I merge the table based on userGroupCode and userGroupDesc.
I am feeling the code is not that performance optimised, How could I optimised this code.
Thank you in advance.
Ola,
You can group by using Map taking id as key and value as object ( to be aggregated into) . For example:
if(map.containes(key))
{
get object from map and do Ops.
}
else
{
1. Create new object
2. Do set Ops on Object
3. Add to map.
}
You basically have 2 solutions,
Write a query that returns all results with joins and do filtering in java, quite easy to achieve with 2 maps (one for the UserGroup the other for the Employee.
Write a query and aggregate the duplicates using list in the query itself.
SELECT ug.userGroupCode, ug.userGroupDesc, up.userPreference, emp.employee_id,emp.name,emp.role
FROM dbo.UserGroup_link ug
INNER JOIN dbo.UserPreference up ON ug.userGroupCode = up.userGroupCode
INNER JOIN dbo.employee emp ON ug.userGroupCode = emp.userGroupCode
Then use a RowCallbackHandler to achieve what you want (instead of a ResultSetExtractor.
Map<String, UserGroup> userGroups = new HashMap<>;
Map<Integer, Employee> employees = new HashMap<>;
jdbc.query(query, (rs) -> {
String userGroupCode = rs.getString("userGroupCode");
String emp_id = rs.getString("employee_id");
UserGroupMapping ugm userGroups.computeIfAbsent(userGroupCode, {
UserGroupMapping ugm1 = new UserGroupMapping();
ugm1.setUserGroupCode(userGroupCode);
ugm1.setUserGroupDesc(rs.getString("userGroupDesc");
ugm1.setUserPreference(new ArrayList<>());
ugm1.getEmployee(new ArrayList<>());
return ugm1;
});
ugm.getUserPreference().add(rs.getString("userPreference"));
Employee emp = employees.computeIfAbsent(emp_id, {
Employee emp1 = new Employee();
emp1.setName(rs.getString("name"));
emp1.setRole(new ArrayList<>());
ugm.getEmployee().add(emp);
return emp1;
});
emp.getRole().add(rs.getString("role"));
});
return userGroups.values();
The above code will get all UserGroupMapping objects from the result including all the Employee instances. The temporary maps are needed to determine if record has already been shown.
Another solution would be to use list in your query and some GROUP BY statement to let the query do part of the aggregation. That way you could make it a bit easier to create an Employee.

Java 8 Stream compare list of two objects

I am looking for an example to filter two lists and create a list that contains only a subset based on condition. For example
List-1 contains list of User objects
List-2 contains list of PaidUser
Now I need to filter and prepare a list of unpaid users. Below code produce list with all elements but expectation is only "ABC" . Please assist
class User {
private String userName;
private String age;
public String getAge(){
return age;
}
public String getUserName(){
return userName;
}
}
class PaidUser{
private String userName;
private double amt;
public String getUserName(){
return userName;
}
}
List<User> users = new ArrayList<>();
User u = new User();
u.age = "12";
u.userName = "XYZ";
users.add(u);
u.age = "12";
u.userName = "ABC";
users.add(u);
List<PaidUser> paids = new ArrayList<>();
PaidUser paid = new PaidUser();
paid.userName = "XYZ";
paid.amt = 1;
paids.add(paid);
List<User> unpaidUsers = users.stream()
.filter(e -> (!paids.stream()
.anyMatch(p-> p.getUserName().equals(e.getUserName()))))
.collect(Collectors.toList());
The issue is not with your logic rather in the way you add User to your input list.
After you add an object, you mutate the same object and add the same reference
users.add(u);
u.age = "12";
u.userName = "ABC";
users.add(u);
After executing the above lines your list has the same User reference twice (User with name ABC and age 12).
Change it to
User u = new User();
u.age = "12";
u.userName = "XYZ";
users.add(u);
u = new User(); //Create new User object
u.age = "12";
u.userName = "ABC";
users.add(u);

How to add/sum two values in hibernate/java

Hello guys i need your help.
I want to add a stock to my existing quantity.
For example in my jsp form, i have to input stock to be added in my quantity. If i have 10 quantity and i input 5stock. The quantity will now become 15.
My Controller looks this:
#RequestMapping(method = RequestMethod.POST, value = "/updateUser")
public String updateUser(HttpServletRequest request, ModelMap map) {
String searchId = request.getParameter("userId");
String searchProductName = request.getParameter("productName");
String searchQuantity = request.getParameter("quantity");
String searchPrice = request.getParameter("price");
String searchDdes = request.getParameter("des");
String searchStock = request.getParameter("stock");
String searchDate = request.getParameter("date");
Product updateableUser = new Product();
updateableUser.setPname(searchProductName);
updateableUser.setPquantity(searchQuantity);
updateableUser.setPprice(searchPrice);
updateableUser.setPdes(searchDdes);
updateableUser.setPstock(searchStock);
updateableUser.setPdate(searchDate);
System.out.println("PRODUCT ID += " + searchId);
productService.updateUser(updateableUser);
return this.searchUsers(request, map, null, null);
}
My DaoImpl
public void updateUser(Product product) {
EntityManager entityManager = transactionManager.getEntityManagerFactory().createEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
try {
transaction.begin();
entityManager.merge(product);
transaction.commit();
} catch (Exception exc) {
exc.printStackTrace();
if (transaction.isActive())
transaction.rollback();
} finally {
if (entityManager.isOpen())
entityManager.close();
}
System.out.println("MANA UG UPDATE");
}
I try this statement in my Controller:
updateableUser.setPquantity(searchQuantity+searchStock);
But when i have 10quantity and i input 5stock the result will become 105.
What will i do to add this two values??
This looks like the + symbol is being used on two strings rather than two integers which is concatenating the strings together instead of adding them together as Integers. You would need to make them into Integers in order to add them together in this manner.
E.g.
int quantity = Integer.valueOf(searchQuantity)+ Integer.valueOf(searchStock)
updateableUser.setPquantity(String.valueOf(quantity));
Of course, this might throw an exception unless you have already validated that they numbers are actually integers.

Why doesn't this .equals() work?

I'm working in Eclipse (Android). In the following blocks, EmployeeInt and RestaurantInt are data types and query() opens a connection to the database and parses the results. When I print the query results, I get identical strings, but the boolean is still false. I've tried trimming the strings, but that didn't help.
public boolean verifyEmployee(String email, String password) {
ArrayList<EmployeeInt> employeeEmailID = query("SELECT employeeID FROM employees WHERE emailAddress = \'"+email+"\'");
ArrayList<EmployeeInt> employeePasswordID = query("SELECT employeeID FROM employees WHERE password = \'"+password+"\'");
String stringEmployeeEmailID = employeeEmailID.toString();
String stringEmployeePasswordID = employeePasswordID.toString();
if(stringEmployeeEmailID.equals(stringEmployeePasswordID)) {
return true;
} else {
return false;
}
}
Executing the above gives me false, while executing the following block (virtually identical) gives me true.
public boolean verifyRestaurant(String email, String password) {
ArrayList<RestaurantInt> restaurantEmailID = query("SELECT restaurantID FROM restaurants WHERE emailAddress = \'"+email+"\'");
ArrayList<RestaurantInt> restaurantPasswordID = query("SELECT restaurantID FROM restaurants WHERE password = \'"+password+"\'");
String stringRestaurantEmailID = restaurantEmailID.toString();
String stringRestaurantPasswordID = restaurantPasswordID.toString();
if(stringRestaurantEmailID.equals(stringRestaurantPasswordID)) {
return true;
} else {
return false;
}
}
Can anyone point out my mistake?
EDIT
I changed it to this and it worked:
public boolean verifyEmployee(String email, String password) {
ArrayList<EmployeeInt> employeeEmailID = query("SELECT * FROM employees WHERE emailAddress = \'"+email+"\'");
ArrayList<EmployeeInt> employeePasswordID = query("SELECT * FROM employees WHERE password = \'"+password+"\'");
int intEmployeeEmailID = employeeEmailID.get(0).getID();
int intEmployeePasswordID = employeePasswordID.get(0).getID();
if(intEmployeeEmailID==intEmployeePasswordID) {
return true;
} else {
return false;
}
}
I know I could also use return (condition), but I would like to add some messages if the login fails, something like:
System.err.println("email address and password do not correspond");
I'm not making an app to publish, it's merely for an assignment. Thanks for the help!
You are calling toString() on an ArrayList. Two different ArrayList objects will return two different toString() strings. You probably meant to get the first element of the ArrayList, and convert THAT to a string.
Example
EmployeeInt is your custom object. In my example, I assume it has some int field that can be retreived with getID().
ArrayList<EmployeeInt> idList = query("SELECT employeeID FROM employees WHERE emailAddress = \'"+email+"\'");
int ID = idList.get(0).getID();
stringEmployeeEmailID = String.valueOf(ID);
This may be easier to read than code:
query() returns an ArrayList
We extract the first element of the ArrayList - this is the part you left out
We get the ID of that element
We convert it to a String

Categories

Resources