how to do edit in spring mvc using only 2 jsp pages - spring

My code below,
#RequestMapping("/employee/edit")
public ModelAndView editEmp(#RequestParam int emp_Id, #RequestParam boolean flag,
#ModelAttribute Employee emp) {
emp = empService.getEmp(emp_Id);
List<String> cityList = new ArrayList<String>();
cityList.add("Hyderabad");
cityList.add("Secunderabad");
Map<String, Object> map = new HashMap<String, Object>();
map.put("cityList", cityList);
map.put("emp", emp);
return new ModelAndView("employee", "map", map);
}

Related

Convert to simplejdbccall resultset to java objects

I am calling DB2 procedure which takes a input parameter and returns a resultset.
How can i map the O/P to my pojo class.
I have to map the result to nexted pojo classes.
simpleJdbcCall = new SimpleJdbcCall(jdbctemplate)
.withSchemaName("myschema")
.withProcedureName("DB2-PROC")
.declareParameters(
new SqlParameter("1", Types.VARCHAR)
);
Map<String, Object> map = simpleJdbcCall.execute("2020-01-01");
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println("Entry value is " + entry.getValue() );
}
//my o/p
Entry value is [{Col_1=abc, col_2=abc,col_2=xyz, col_2=abc},....];
you can use returningResultSet(parameterName, rowMapper) method to map values to object.
Here some reference code:
SimpleJdbcCall procedureActor = new SimpleJdbcCall(dataSource)
.withSchemaName("myschema")
.withProcedureName("DB2-PROC")
.declareParameters(
new SqlParameter("1", Types.VARCHAR))
.returningResultSet("mapObjRefrence", new RowMapper<Contact>() {
#Override
public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
YourPojo pojo = new YourPojo();
pojo.setId(rs.getInt("col_1"));
pojo.setName(rs.getString("col_2"));
pojo.setEmail(rs.getString("col_2"));
pojo.setAddress(rs.getString("col_3"));
pojo.setTelephone(rs.getString("col_4"));
return contact;
}
});
Map<String, Object> out = procedureActor.execute("2020-01-01");
List<YourPojo> listPojos = (List<YourPojo>) out.get("mapObjRefrence");
Also you can check for multi table results: How to get multi table results using SimpleJDBCCall in spring?

Conditional IN from DynamoDb not working on java

I am working with DynamoDB with Spring Boot 2.1, and I'm facing an error when I need o user the clause IN during the conditional evaluation. Even with lines that fulfill the requirements, the query result is empty.
How can I return the lines from the table after explicit the result within the IN clause ?
public class DynamoRepository {
private final DynamoDBMapper dynamoDBMapper;
public Optional<List<USER>> query(String id) {
Map<String, String> ean = new HashMap<>();
ean.put("#status", "status");
Map<String, AttributeValue> eav = new HashMap<>();
eav.put(":id", new AttributeValue().withS(documento));
DynamoDBQueryExpression<USER> queryExpression = new DynamoDBQueryExpression<USER>()
.withKeyConditionExpression("id = :id")
.withFilterExpression("#status in (ACTIVE, PENDING)")
.withExpressionAttributeNames(ean)
.withExpressionAttributeValues(eav);
List<USER> query = dynamoDBMapper.query(USER.class, queryExpression);
return query.isEmpty() ? Optional.empty() : Optional.of(query);
}
}
After taking a while, my solution was to define the status' values as Expression Attribute Values like the code below
public class DynamoRepository {
private final DynamoDBMapper dynamoDBMapper;
public Optional<List<USER>> query(String id) {
Map<String, String> ean = new HashMap<>();
ean.put("#status", "status");
Map<String, AttributeValue> eav = new HashMap<>();
eav.put(":id", new AttributeValue().withS(documento));
eav.put(":active", new AttributeValue().withS("ACTIVE"));
eav.put(":pending", new AttributeValue().withS("PENDING"));
DynamoDBQueryExpression<USER> queryExpression = new DynamoDBQueryExpression<USER>()
.withKeyConditionExpression("id = :id")
.withFilterExpression("#status in (:active, :pending)")
.withExpressionAttributeNames(ean)
.withExpressionAttributeValues(eav);
List<USER> query = dynamoDBMapper.query(USER.class, queryExpression);
return query.isEmpty() ? Optional.empty() : Optional.of(query);
}
}

I insert a null column and in the next I save the data

because when I make a record in my form to the database first I register a null column and after the value that I insert, I am using spring
#RequestMapping("/listaPalabras")
public ModelAndView listaPalabras(Palabras uploadItem, HttpServletRequest request) {
ModelAndView modelAndView = new ModelAndView("listaPalabras");
List<Palabras> list = palService.listPalabras();
return new ModelAndView("listaPalabras", "list", list);
}
#RequestMapping(value = "/agregarPalabras", method = RequestMethod.GET)
public String productCreate(#ModelAttribute("palabra") Palabras palabras) {
palService.saveOrUpdate(palabras);
return "agregarPalabras";
}
this is result

Spring simplejdbc Stored procedure using resultset Extractor

I am new to Spring and i'm learning it now. Meanwhile i am stuck at a particular place . i am able to execute the stored procedure but its not returning me any result back .please guide me .I'm using sybase database . The stored procedure contains two parameters one is for the input and the other is the output.
public String getGetNextIdQuery(String string, String region){
String custId = "";
JdbcTemplate jtempl = jdbcTemplateMap.get(region);
Map<String, Object> inParams = new HashMap<String, Object>();
String nextId = "?";
inParams.put("len", string);
inParams.put("acct_id",nextId);
SimpleJdbcCall simpleJdbcCall = new SimpleJdbcCall(jtempl).
withProcedureName("pr_acct_id")
.withReturnValue()
.withReturnValue().withoutProcedureColumnMetaDataAccess()
.declareParameters(new SqlOutParameter("RETURN", java.sql.Types.VARCHAR))
.declareParameters(new SqlParameter("len", java.sql.Types.SMALLINT))
.declareParameters(new SqlParameter("acct_id", java.sql.Types.VARCHAR))
.declareParameters(new SqlReturnResultSet("RESULT", new ResultSetExtractor<String>() {
#Override
public String extractData(
ResultSet arg0)
throws SQLException {
String custId = "";
int i = 0;
while(arg0.next()) {
System.out.println(i++);
custId = arg0.getString("acct_id");
}
return custId;
}
}));
Map<String, Object> result = simpleJdbcCall.execute(inParams);
System.out.println((String)result.get("RESULT"));
custId = (String)result.get("RESULT");
return custId;
}

Data not retrieving after saving in database in hibernate 4

I am using Hibernate 4 with Spring 4. I have created my own session factory and used Hibernate Transaction Manager. I have a problem while retrieving the data after saving.
I am saving the data using ProcedureCall and in every method I am opening the session and closing the session. What is the problem? If I remove session.close() then it is working fine.
public Map<String, Object> savePurchaseOrderInvoiceDetail(String dataString, String order_no,String event, HttpSession hs) throws SQLException, ParseException {
HibernateTransactionManager htmLocal = (HibernateTransactionManager) hs.getAttribute("HibernateTransactionManager");
Session session = htmLocal.getSessionFactory().openSession();
Transaction tx = getTransaction(session);
ProcedureCall qry = session.createStoredProcedureCall("purchase_order_invoice_api");
qry.registerParameter(0, String.class, ParameterMode.IN).bindValue(event);
qry.registerParameter(1, String.class, ParameterMode.IN).bindValue(dataString);
qry.registerParameter(2, String.class, ParameterMode.OUT);
qry.registerParameter(3, String.class, ParameterMode.OUT);
qry.registerParameter(4, Integer.class, ParameterMode.OUT);
qry.registerParameter(5, String.class, ParameterMode.OUT);
ProcedureOutputs output = qry.getOutputs();
String msg = (String) output.getOutputParameterValue(2);
String voucheNo=(String) output.getOutputParameterValue(3);
int invoiceId=(int) output.getOutputParameterValue(4);
String status=(String) output.getOutputParameterValue(5);
Map<String, Object>map=new HashMap<String, Object>();
map.put("msg", msg);
map.put("voucherNo", voucheNo);
map.put("lastInvoiceId", invoiceId);
map.put("status", status);
tx.commit();
session.close();
return map;
}
public Map<String, Object> getInvoiceDetails(String invoicedId,HttpSession hs) throws Exception{
HibernateTransactionManager htmLocal = (HibernateTransactionManager) hs.getAttribute("HibernateTransactionManager");
Session session = htmLocal.getSessionFactory().openSession();
final Map<String, Object>map=new HashMap<String, Object>();
String company=(String) hs.getAttribute("company");
int invoiceIdInt=Integer.valueOf(invoicedId);
String qry = "select inv.*,get_supplier_name(inv.Company,inv.Identity) AS CUSTOMER_NAME from invoice_tab inv";
Query query = session.createSQLQuery(qry).addEntity(Invoice.class);
query.setCacheable(false);
List<Invoice> invoiceList = query.list();
for (int i = 0; i < invoiceList.size(); i++) {
Invoice invoiceObj=invoiceList.get(i);
//Business logic
}
session.close();
return map;
}
You are trying hard to to use Spring not to mention the fact that you are having a service (or maybe a repository) dependent on the fact that it is a web application. Both things are bad.
Add the #Transactional annotation to the class containing those methods and enable annotation driven transaction management. Instead of passing around the HttpSession simply inject your dependencies, in this case the SessionFactory.
Don't create sessions yourself use the current session, i.e sessionFactory.getCurrentSession() to obtain a transactional session.
#Service
#Transactional
public class YourService {
private final SessionFactory sessionFactory;
public YourService(SessionFactory sf) {
this.sessionFactory=sf;
}
public Map<String, Object> savePurchaseOrderInvoiceDetail(String dataString, String order_no,String event) throws SQLException, ParseException {
Session session = sessionFactory.getCurrentSession();
ProcedureCall qry = session.createStoredProcedureCall("purchase_order_invoice_api");
qry.registerParameter(0, String.class, ParameterMode.IN).bindValue(event);
qry.registerParameter(1, String.class, ParameterMode.IN).bindValue(dataString);
qry.registerParameter(2, String.class, ParameterMode.OUT);
qry.registerParameter(3, String.class, ParameterMode.OUT);
qry.registerParameter(4, Integer.class, ParameterMode.OUT);
qry.registerParameter(5, String.class, ParameterMode.OUT);
ProcedureOutputs output = qry.getOutputs();
String msg = (String) output.getOutputParameterValue(2);
String voucheNo=(String) output.getOutputParameterValue(3);
int invoiceId=(int) output.getOutputParameterValue(4);
String status=(String) output.getOutputParameterValue(5);
Map<String, Object>map=new HashMap<String, Object>();
map.put("msg", msg);
map.put("voucherNo", voucheNo);
map.put("lastInvoiceId", invoiceId);
map.put("status", status);
return map;
}
public Map<String, Object> getInvoiceDetails(int invoicedId, String company) throws Exception{
Session session = sessionFactory.getCurrentSession();
final Map<String, Object>map=new HashMap<String, Object>();
String qry = "select inv.*,get_supplier_name(inv.Company,inv.Identity) AS CUSTOMER_NAME from invoice_tab inv";
Query query = session.createSQLQuery(qry).addEntity(Invoice.class);
query.setCacheable(false);
List<Invoice> invoiceList = query.list();
for (int i = 0; i < invoiceList.size(); i++) {
Invoice invoiceObj=invoiceList.get(i);
//Business logic
}
return map;
}
}
Something like the above.
What I don't really get is why you are even using hibernate as you are creating your own queries and don't use HQL or anything to get entities. The only thing you use hibernate for is mapping and that can be done with plain SQL also, adding hibernate to your project just for the mapping of your sql results is bit overkill in my book.

Resources