How to convert createQuery response in key value pair? [duplicate] - java

I am developing an application in struts 2 and hibernate 3.
I have 3 tables
Inspection
InspectionMission
Timeline
Inspection is associated with InspectionMission and InspectionMission is associated with Timeline.
Now I have following problem. I have written following query in HQL
public List getQuartewiseInspectionList(){
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Query q = session.createQuery(
"select count(i.inspectionId) as tot_inspections,t.year,t.quarter" +
" From Inspection as i " +
" inner join i.inspectionMission as im inner join im.timeline as t" +
" GROUP by t.year,t.quarter");
return q.list();
}
I want to fetch result as following
result[0][tot_inspections] = "6"
result[0][year] = "2009";
result[0][quarter] = "Q2";
result[1][tot_inspections] = "3"
result[1][year] = "2009";
result[1][quarter] = "Q3";
and so on so that I can display it in jsp struts as follows:
In JSP I have written following code
<table border="1">
<s:iterator value="result" status="status">
<tr class="<s:if test="#status.even">even</s:if><s:else>odd</s:else>">
<td class="nowrap"><s:property value="tot_inspections" /></td>
<td class="nowrap"><s:property value="year" /></td>
<td class="nowrap"><s:property value="quarter" /></td>
</tr>
</s:iterator>
</table>
Can anyone here help me?

You have to use the "new map" syntax (Hibernate Reference paragraph 14.6)
select new map(count(i.inspectionId) as tot_inspections, t.year as year, t.quarter as quarter) from ...
The rest of the query is the same. This will return a list of maps, where the key is the alias of the "column".

Another solution would be to define a data object just for displaying those results and let Hibernate create instances of those on the fly. This class would just need a matching constructor.
Example class (getters and fields omitted)
public class InspectionCount() {
// fields
public InspectionCount(int count, int year, int quarter) {
// initialize instance
}
// getters
}
The query would then look
select new InspectionCount(count(i.inspectionId), t.year, t.quarter)
from Inspection as i
inner join i.inspectionMission as im inner join im.timeline as t
group by t.year,t.quarter
As a result you would get a List of InspectionCounts.

Related

Get the max value using kotlin-exposed

I want to simulate this query using kotlin exposed framework:
SELECT max(episodes.season_number) FROM episodes WHERE episodes.parent_id = 944947
I tried the next one query:
fun countSeasonsForParentId(id: Int) = transaction {
EpisodeTable.slice(EpisodeTable.season)
.select { EpisodeTable.parentId eq id }
.map { it[EpisodeTable.season] }.maxOrNull()
}
But this query just results in:
SELECT episodes.season_number FROM episodes WHERE episodes.parent_id = 944947
and the max value is selected in the code.
How to perform finding max value on the side of the database and map it to Int?
I tried similar query and I believe it fits your need.
The query is:
Reservations
.slice(Reservations.date.max())
.select { Reservations.note eq "it" }
.maxByOrNull { Reservations.date }
And it generates SQL query:
SELECT MAX(reservations."date") FROM reservations WHERE reservations.note = 'it'
Your query can be used as:
EpisodeTable
.slice(EpisodeTable.season.max())
.select { EpisodeTable.parentId eq id }
.maxByOrNull { EpisodeTable.season }
?.get(EpisodeTable.season.max())
Alternative, for extracting one value seems more appropriate:
EpisodeTable
.slice(EpisodeTable.season.max())
.select { EpisodeTable.parentId eq id }
.firstOrNull()
?.get(EpisodeTable.season.max())

How retrieve client selection from HTML select tag that is populated with info from database?

I've populated a tag with data from the db with this code:
<select name="course">
<!-- This uses Velocity Template Language. This code loops through -->
<!-- the map of the query result and populates the list -->
#foreach($course in $courses)
<option value="$!{$course.get("coursename")}">$course.get("coursename")</option>
#end
</select>
As you can see, the value of each option is also a variable. I tried the [select name="course"] but that didn't work. This form is handled by this method:
//We're using the Sparkjava framework
public static Route addFlashCard = (Request req, Response res) -> {
Map<String, Object> model = new HashMap<>();
String uname = req.session().attribute("currentUser");
String question = req.queryParams("question");
String answer = req.queryParams("answer");
String course = req.queryParams("course");
boolean result = PreparedQueries.addFlashCard(question, answer, course, uname);
if(!result)
model.put("fail", result);
else
model.put("success", result);
return new VelocityTemplateEngine().render(new ModelAndView(model, "html/flashcard.html"));
};
I know there isn't an SQL error because none of my try-catch blocks spit out an error. What do I need to do to get the client selection?
If i understand well, you just want to select the value of that select element (?). If so, I think you mistook in your selector, instead of:
[select name="course"]
it should be:
select[name="course"]
Tell me if I misunderstood your question I will edit it

struts-tags iterator is duplicating rows

I am outputting data to an html table using a struts-tags iterator. It works for the most part but for a few rows, it duplicates the previous row instead of putting in the correct data. Very strange inconsistency.
Here is the html:
<s:iterator value="result">
<tr>
<td><s:property value="timestamp"/></td>
<td><s:property value="targetId"/></td>
<td><s:property value="sourceIp"/></td>
<td><s:property value="transactionType"/></td>
<td><s:property value="status"/></td>
</tr>
</s:iterator>
"result" is defined in the java controller:
private List<AuditData> result
and is populated by a hibernate query like so:
session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = buildQuery2(session);
result = criteria.list();
Here is an example output of the problem:
10/3/16 8:17:31 PM.000 hanogreg 10.10.10.10 Pwd Reset Success
10/3/16 8:17:31 PM.000 hanogreg 10.10.10.10 Pwd Reset Success
The second row is a duplicate of the first but the database shows the second entry should say "Pwd Change", not "Pwd Reset".
Does anyone have any ideas as to what could be causing this inconsistent behavior?
Edit: This is a hibernate issue, not a struts issue as I can see "result" already contains the duplicate row instead of the real row. Here is buildQuery2() which creates the hibernate criteria:
private Criteria buildQuery2(Session session) throws ParseException {
Criteria criteria = session.createCriteria(AuditData.class);
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
if (!fromDate.equals("All")) {
Date fDate = df.parse(fromDate);
criteria.add(Restrictions.ge("timestamp", fDate));
}
if (!toDate.equals("All")) {
Date tDate = df.parse(toDate);
actionlogger.debug("toDate=" +toDate +", tDate="+tDate.toString());
tDate = getEndOfDayDate(tDate); //set the time to the last millisecond of the day so all other times will be less
criteria.add(Restrictions.le("timestamp", tDate));
}
if (!csgUsername.equals("All")) criteria.add(Restrictions.eq("target_id",csgUsername));
if (!sourceIp.equals("All")) criteria.add(Restrictions.eq("source_ip",sourceIp));
if (!transactionType.equals("All")) criteria.add(Restrictions.eq("transaction_type",transactionType));
if (!status.equals("All")) criteria.add(Restrictions.eq("status",status));
criteria.addOrder(Order.asc("timestamp"));
return criteria;
}
Since I was unable to figure out why this was happening, I was forced to re-write the code to do the same thing without hibernate and got it to work correctly.

spring mvc dynamic list binding particular value becomes empty

I have a very peculiar problem. I am developing a web application in Java and Spring MVC. I have a row that can be duplicated dynamically by the user on the press of a button. Each row has around 10 fields. I am binding these rows as list of objects in the backing bean and initializing this list as a lazy list in the bean. Now, it has been working fine till now but the user tried to enter 12 rows and on the 12th row, i.e., the 11th iteration(the iteration starting from 0), the 5th field becomes empty, although the user enters values and all the other fields retain their values. Since the binding happens with name, I have checked the name of the field, it is consistent with the rest of the fields in the same row and the rest of the rows. I am unable to debug and rectify the issue. This is affecting the code in production.
I can provide whatever code snippets are required.
Can somebody please help me with this. Thanks in advance.
EDIT: I tried executing the same code on a different server and it works fine there but still persists on the live server. And the problem seems to be only in the 11th iteration's 5th field. Could it be a problem with the server
Adding code:
JSP:
<c:forEach items="${addProposal.requirements}" var="req" varStatus="status">
<!--Rest of the fields-->
<form:input path="requirements[${status.index}].sampleSize" id="r_sample${status.index}" value="${addProposal.requirements[status.index].maximumFeasibility}" class="inptform2" style="width:65px;" size="10" onchange="functions();"/>
<!--Rest of the fields-->
<td width="57" align="left" valign="middle" id="btn-close" class="btn-remove">' +
'<a href="javascript:void(0)"><img src="images/btncross.png" width="18" height="17" border="0" />' +
'</a>
</td>
</c:forEach>
Javascript:
$(document).ready(function(){
//Add more dynamic rows
$("#addMore").click(function() {
var tr_temp=$("#requirement tr:first").clone();
//rest of the fields code
tr_temp.find("#r_sample0").each(function() {
$(this).attr({
'id': function(_, id) { return 'r_sample' + i},
'name': function(_, name) { return 'requirements[' + i + '].sampleSize'},
'value': ''
});
}).end();
tr_temp.find("td:last").remove();
tr_temp.append(btn_close);
tr_temp.appendTo("#requirement");
i++;
});
//To remove a dynamically added row
$("#btn-close").live('click',function(){
doNotDel=false;
count=0;
//To fetch the values of the Input Fields
$(this).parent().find("input").each(function(){
count++;
var value = $(this).val();
var id=$(this).attr('id');
if(id.indexOf("r_total")==-1){
//Skip the minutes and currency column
if(id.indexOf("minutes")==-1 && id.indexOf("currencyValF")==-1 && id.indexOf("currencyVal")==-1){
if(value!=""){
doNotDel=true;
return false; //breaks the .each loop
}
}
}
});
if(doNotDel==false){
$(this).parent().remove();
}
});
});
Bean:
private List<RequirementBean> requirements;
//in constructor
requirements = LazyList.decorate(
new ArrayList<RequirementBean>()
, new InstantiateFactory(RequirementBean.class));
Controller:
#RequestMapping(value="/addProposal", method=RequestMethod.POST)
public String addProposal(#ModelAttribute("addProposal") ProposalBean proposal, ModelMap model){
RequirementBean req;
List<RequirementBean> reqmtList;
System.out.println("Before empty rows");
reqmtList = proposal.getRequirements();
for(int i=0; i<reqmtList.size(); i++){
req = reqmtList.get(i);
if(req.getCountry()!=null){
System.out.println("sample size " + i + " :" + req.getSampleSize());
}
}
}
EDIT:
I tried changing the value of the 4th row in the same column, and now the code seems to work. I am still not able to understand what is the issue.
Hope this gives more clarity. Please help me.

Delete item from Cart -Spring MVC

I am developing a small application using spring mvc where I need to have option to delete each item from cart (in case customer feels he donot need after adding to cart).
I have got a "delete" button below each item item.(The items added are in a list).My pupose is when I click delete button against a particular item only that item should be removed from the cart.
I have written some code but it is remove lastest added items from cart and not required one.
I know my mistake but not able to proceed further.Here is what I implemented.
This is jsp :
<c:forEach items="${cart}" var="nextMovie">
<li>
<h2>${nextMovie.title}</h2>
</li>
<h2>Price</h2>
<h2>${nextMovie.price}</h2>
<c:set var="totalPrice" value="${0}" />
<c:forEach var="nextMovie" items="${cart}">
<c:set var="totalPrice" value="${totalPrice + nextMovie.price}"/>
</c:forEach>
<form method='post' action='<c:url value="removeFromCart.do"/>'>
<input type='image' src='Delete.png'/>
<input type='hidden' name='id' value='${nextMovie.id}'/>
</form>
</c:forEach>
This is my controller:
#RequestMapping("/removeFromCart")
public ModelAndView removeFromCart(HttpSession session) {
ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
if (cart == null) {
cart = new ShoppingCart();
}
List<Movie> allMovies = cart.getAllItems();
for(int i= 0;i<allMovies.size();i++)
{
allMovies.remove(i);
}
return new ModelAndView("/cartContents.jsp", "cart", allMovies);
}
Please suggest me how I will be able to delete the element again the delete button from the list.
Thanks
Maruthi
[HttpPost]
[Route("~/CartDetail/DeleteCartDetail")]
public ActionResult DeleteCartDetail(CartDetailModel model)
{
var response = _cartDetailService.DeleteCartItem(model.Id);
return Json(new
{
success = response.Success,
message = response.Message
});
}
}
I am importing my data from service DeleteCartItem
Here is service code
public BaseResponse DeleteCartItem(int cartDetailId)
{
var response = new BaseResponse();
try
{
var itemCart = _context.CartDetails.FirstOrDefault(x => x.Id == cartDetailId);
if (itemCart == null)
{
response.Message = "This item does not exist in the cart.";
return response;
}
_context.CartDetails.Remove(itemCart);
_context.SaveChanges();
response.Success = true;
}
catch (Exception exception)
{
response.Message = "Some error occured : " + exception.ToString();
}
return response;
}
Your JSP has nested <c:forEach> tags, with both containing the same items expression. Either you don't need 2 of them of else you need to close the first one before starting the second.
Your application has some problems:
First, your problem is because you are using the same var attribute name, for your both foreach tags. The first tag defines an attribute named nextMovie in its scope, the second foreach which is nested within first, defines the same attribute name, and then iterates, so when its iteration completes, nextMovie will be last element in the list, so ${nextMovie.id} will be last element's id.
Second,
List<Movie> allMovies = cart.getAllItems();
for (int i= 0;i<allMovies.size();i++) {
allMovies.remove(i);
}
is equivalent of allMovies.clear(), isn't it? So you are removing all items form list, what else do you need?
Third, next problem is you have an object of type ShoppingCart in your session which is named cart, and you add an object of type List<Movie> to your model with the same name; although when EL processor tries to resolve a name request has a more priority than session, but believe me it is much better to rename one.
Forth, why are you calculating 'totalPrice' in each iteration? And what is its use?

Categories