How to update a record after extracting - java

private List<String> getSCFData(int trdCustomerKy, Date lastRunDate, Date currentDate) throws TradeException {
List<String> reportData = null;
String paymentDate = EMPTY_STRING;
String partyId = EMPTY_STRING;
YOWDAO hdDAO = new YOWDAO(mConnection);
List<YOWSCFExtractData> reportItems = hdDAO.getSCFData(trdCustomerKy, lastRunDate, currentDate);
if (null != reportItems && reportItems.size() > 0) {
reportData = new ArrayList<String>();
mTracer.log("Total records retrieved: " + reportItems.size());
for (YOWSCFExtractData data : reportItems) {
String Source = (null != data.getSource()) ? data.getSource() : BLANK_STRING;
String paymentCurrencyCd = (null != data.getPaymentCurrencyCd()) ? data.getPaymentCurrencyCd()
: BLANK_STRING;
String sellerName = (null != data.getSellerName()) ? data.getSellerName() : BLANK_STRING;
String paymentAmount = (null != data.getPaymentAmount()) ? data.getPaymentAmount() : BLANK_STRING;
if (null != data.getPaymentDate()) {
paymentDate = DateUtil.formatDate(data.getPaymentDate());
}
if (null != data.getapplCifId()) {
partyId = hdDAO.getPartyId(mConfiguration.getCustomerKy(), data.getapplCifId());
}
String dataRow = StringUtils.join(new String[] { Source, data.getBankRef(), partyId, sellerName,
data.getPartyId(), paymentAmount, paymentDate, paymentCurrencyCd}, COMMA);
reportData.add(dataRow);
}
}
return reportData;
}
I am extracting the data from oracle database. I want to update the record of a column once it is fetched to a string. for example when I had extracted data.getBanref() then I want to set it some string back in database. how would I do that? I am using hibernate........

What you can do is set the object data whatever values you want and then save it in the hibernate. If you want to update then use session.saveOrUpdate() or if you want to save a new record then use session.save(). Hope that helps!

You can write a hibernate query
Update table_Name column_Name and set it to whatever you want and call this query in your program. It will be easier i think so

Related

How to implement logic using elasticsearch Pagination using ElasticsearchRepository in java

Is there any way to use ElasticsearchRepository which extends from PagingAndSortingRepository. This allows built-in support for pagination and sorting.
But I am not able to change my implementation to use ElasticsearchRepository. I just want to know how to apply:
How to use Post Search
How to use esQuery which basically providing Search query
String esQuery = String.format(searchTextQuery, startDate, endDate, formattedQueries);
How to use that Post URI which I m getting as below:
Request request = new Request("GET", "/" + user.getUserId() + "/_search");
So with all the above, how to use Pagination with ElasticsearchRepository
Below is my service code:
public List getResponses(ZonedDateTime startDate, ZonedDateTime endDate,
String cat, FieldFilterVM filter, String query) throws IOException {
User user = (User)
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Request request = new Request("GET", "/" + user.getUserId() + "/_search");
List<String> matchQueries = new ArrayList<>();
matchQueries.addAll(formatCategoryQuery(cat));
matchQueries.addAll(formatFilterQuery(filter, false));
if (query != null && query.length() > 0) {
matchQueries.add(String.format(textFilterQuery, query));
}
StringBuilder formattedQueries = new StringBuilder();
for (int i = 0; i < matchQueries.size(); i++) {
formattedQueries.append(',');
formattedQueries.append(matchQueries.get(i));
}
String esQuery = String.format(searchTextQuery, startDate, endDate,
formattedQueries);
request.setJsonEntity(esQuery);
Response response =
elasticSearchService.getClient().getLowLevelClient().performRequest(request);
String responseBody = IOUtils.toString(response.getEntity().getContent(),
"UTF-8");
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(responseBody, new TypeReference<Map>() {
});
List matchedTextResponses = new ArrayList();
if (map != null) {
List<Map> textResponses = (List<Map>) ((Map)
map.get("hits")).get("hits");
for (Map textResponse : textResponses) {
}
}
return matchedTextResponses;
}

Spring Hibernate generate dynamic query

I am using hibernate spring where I need to generate query on a condition.
DAO.java
public ReturnData updateUserDetails(Users users, String mailID)
{
if(!users.getImageURL().equals(""))
{
Query query = this.sessionFactory.getCurrentSession().createQuery("UPDATE users SET emailID=:email_ID, name=:name, imageURL=:imageURL WHERE emailID=:emailID")
//setString....
}
else
{
Query query = this.sessionFactory.getCurrentSession().createQuery("UPDATE users SET emailID=:email_ID, name=:name WHERE emailID=:emailID")
//setString....
}
}
In the above code, I check if image also has been uploaded or not. On the basis of this condition, I have to dynamically generate query. I have to rewrite the whole code for query+execution 2 times. Is it the good way, or is there any better way to do this?
You can dynamically append the query conditions to the query string if they are not null. After getting the final list of conditions, you can create Hibernate query.
StringBuilder sqlQuery = new StringBuilder();
Map<String,Object> parameters = new HashMap<String,Object>();
boolean isFirstSearchCriterion = true;
sqlQuery.append("UPDATE users");
if(email_ID!= null && !email_ID.trim().equals("")) {
if(isFirstSearchCriterion) {
sqlQuery.append(" set emailID= :email_ID");
} else {
sqlQuery.append(" and emailID= :email_ID");
}
parameters.put("email_ID",email_ID);
isFirstSearchCriterion = false;
}
if(name!= null && !name.trim().equals("")) {
if(isFirstSearchCriterion) {
sqlQuery.append(" set name= :name");
} else {
sqlQuery.append(" and name= :name");
}
parameters.put("name",name);
isFirstSearchCriterion = false;
}
if(imageURL!= null && !imageURL.trim().equals("")) {
if(isFirstSearchCriterion) {
sqlQuery.append(" set imageURL= :imageURL");
} else {
sqlQuery.append(" and imageURL= :imageURL");
}
parameters.put("imageURL",imageURL);
isFirstSearchCriterion = false;
}
Query query = this.sessionFactory.getCurrentSession().createQuery(sqlQuery);
Set<String> parameterSet = parameters.keySet();
for (Iterator<String> it = parameterSet.iterator(); it.hasNext();) {
String parameter = it.next();
query.setParameter(parameter, parameters.get(parameter));
}
You can simply do without checking empty String, if user has image url it will add in column or else empty url will be pass on.
public ReturnData updateUserDetails(Users users, String mailID)
{
Query query = this.sessionFactory.getCurrentSession().createQuery("UPDATE users SET emailID=:email_ID, name=:name, imageURL=:imageURL WHERE emailID=:emailID")
query.setParameter("imageURL",users.getImageURL(), Hibernate.STRING);
}

Multithreading issues for database insertion

I have a piece of JAVA code that is accessed by multiple threads.
synchronized (this.getClass())
{
System.out.println("stsrt");
certRequest.setRequestNbr(
generateRequestNumber(
certInsuranceRequestAddRq.getAccountInfo().getAccountNumberId()));
System.out.println("outside funcvtion"+certRequest.getRequestNbr());
reqId = Utils.getUniqueId();
certRequest.setRequestId(reqId);
System.out.println(reqId);
ItemIdInfo itemIdInfo = new ItemIdInfo();
itemIdInfo.setInsurerId(certRequest.getRequestId());
certRequest.setItemIdInfo(itemIdInfo);
dao.insert(certRequest);
addAccountRel();
System.out.println("end");
}
the function generateRequestNumber() generates a request number based on the data fetched from two database tables.
public String generateRequestNumber(String accNumber) throws Exception
{
String requestNumber = null;
if (accNumber != null)
{
String SQL_QUERY = "select CERTREQUEST.requestNbr from CertRequest as CERTREQUEST, "
+ "CertActObjRel as certActObjRel where certActObjRel.certificateObjkeyId=CERTREQUEST.requestId "
+ " and certActObjRel.certObjTypeCd=:certObjTypeCd "
+ " and certActObjRel.certAccountId=:accNumber ";
String[] parameterNames = { "certObjTypeCd", "accNumber" };
Object[] parameterVaues = new Object[]
{
Constants.REQUEST_RELATION_CODE, accNumber
};
List<?> resultSet = dao.executeNamedQuery(SQL_QUERY,
parameterNames, parameterVaues);
// List<?> resultSet = dao.retrieveTableData(SQL_QUERY);
if (resultSet != null && resultSet.size() > 0) {
requestNumber = (String) resultSet.get(0);
}
int maxRequestNumber = -1;
if (requestNumber != null && requestNumber.length() > 0) {
maxRequestNumber = maxValue(resultSet.toArray());
requestNumber = Integer.toString(maxRequestNumber + 1);
} else {
requestNumber = Integer.toString(1);
}
System.out.println("inside function request number"+requestNumber);
return requestNumber;
}
return null;
}
The tables CertRequest and CertActObjRel used in generateRequestNumber() are updated by the functions "dao.insert(certRequest);" and "addAccountRel();" used in my initial code respectively. Also the System.out.println() statements used in my initial code have following output.
stsrt
inside function request number73
outside funcvtion73
A1664886-5F84-45A9-AB5F-C69768B83EAD
end
stsrt
inside function request number73
outside funcvtion73
44DAD872-6A1D-4524-8A32-15741FAC0CA9
end
If you notice both the threads run in a synchronized manner, but when the request number is generated , it's the same. My assumption is the database updation for CertRequest and CertActObjRel is done when both the threads finish their execution.
Could anyone help me to fix this?

Splitting a List<string> on the basis of comman ( ,) delimiter and handling NUmberformat exception

I have the following method applyIncentives which takes ListlstIds
public void applyIncentives(List<String> lstIds) throws Exception {
Session session = null;
Transaction tx = null;
String pricingTierId = null;
if (lstIds != null && lstIds.size() > 0) {
for (String lstpricingTierIds : lstIds) {
pricingTierId = lstpricingTierIds.trim();
}
}
try {
session = HibernateSessionFactory.getSession();
tx = session.beginTransaction();
SQLQuery query = session.createSQLQuery("select * from customer.apply_incentives(:pricingTierId)");
query.setString("pricingTierId", pricingTierId);
query.list();
tx.commit();
approveFlag = true;
}
catch (Exception ex) {
log.error("Exception", ex);
}
finally {
if (session != null)
session.close();
}
return approveFlag;
}
I'm passing the pricingTierId from lstIds and passing to the stored proc which accepts an Integer.
While debugging the value of lstIds is "52512,85822" two pricingTierId's separated by comma (,).
Before passing the pricingTierId to the stored Proc I have written the following:
String pricingTierId = null ;
if (lstIds != null && lstIds.size() > 0) {
for (String lstpricingTierIds : lstIds) {
pricingTierId = lstpricingTierIds.trim();
}
}
My questions:
How to split the pricingTierId by delimited comma (,)?
Since I'm passing List List<String> lstIds I can't use pricingTierId = lstpricingTierIds.trim().split(",") directly.
If I change String pricingTierId = null to String[] pricingTierId then
I have error at query.setString("pricingTierId", pricingTierId);
If I use query.setInteger("pricingTierId", Integer.parseInt(pricingTierId)); then I get Numberformat Exception since comma(,) gets passed to the stored proc.
Added the code as suggested
List<String> pricingTierId = null;
if (lstIds != null && lstIds.size() > 0) {
for(String lstpricingTierIds : lstIds) {
pricingTierId = Arrays.asList(lstpricingTierIds.trim().split(","));
}
}
However I'm getting the error at:
query.setString("pricingTierId", pricingTierId);
setString cannot be used for String[]
and I cannot use query.setInteger("pricingTierId", Integer.parseInt(pricingTierId));
as it says change the type of pricingTierId to String.
How about getting it out of the array created from a split and then loop around:
String[] pricingTierIdArray = lstpricingTierIds.trim().split(",");
for(String s : pricingTierIdArray ) {
query.setInteger("pricingTierId", Integer.parseInt(s));
}
The setInteger() method would overwrite the previous value. Unless you change the query only one id can be set.
Or simply just:
String pricingTierIdArray = lstpricingTierIds.trim().split(",")[0]; //This depends on whether you need both values or not.

Parsing LDAP attributes from String in Java

Is there a way to parse attributes from a String? For example, if I have the following:
CN=Doe, John: Markets (LDN),OU=Users,DC=FOOCORP,DC=COM
and would like to get that into an Attributes or set of Attribute-s, is there a utility class one could use that does all the proper escaping, or should I just knock up some implementation of my own?
I have the following code:
String cnBase = "CN=Doe\\, John: Markets (LDN),OU=Users,DC=FOOCORP,DC=COM";
StringTokenizer st = new StringTokenizer(cnBase, "=");
Attributes attributes = new BasicAttributes();
String attributeId = null;
String attributeValue = null;
String previousToken = null;
while (st.hasMoreTokens())
{
String token = st.nextToken();
if (previousToken == null && attributeId == null)
{
// Get the attribute's id
attributeId = token;
continue;
}
if (attributeId != null)
{
if (token.contains(","))
{
attributeValue = token.substring(0, token.lastIndexOf(","));
}
else
{
attributeValue = token;
}
}
if (attributeId != null && attributeValue != null)
{
// Add a new Attribute to the attributes object
Attribute attribute = new BasicAttribute(attributeId, attributeValue);
attributes.put(attribute);
System.out.println(attribute.toString());
attributeId = token.substring(token.lastIndexOf(",") + 1, token.length());
attributeValue = null;
}
previousToken = token;
}
Which I think can be re-written in a smarter way.
JNDI has a class called LdapName (misnamed), which represents a distinguished name. It's based on an obsolete RFC but it might be satisfactory.
see also
LDAP: Mastering Search Filters
LDAP: Search best practices
LDAP: Programming practices

Categories