selectone in mybatis throws nullpointerException - spring

DAO
// Review Total Count
public int reviewTotalCnt() {
System.out.println("========== Review Total Count DAO ==========");
return sqlSession.selectOne("ReviewMapper.reviewTotalCnt");
}
XML
<!-- Review Total Count -->
<select id="reviewTotalCnt" resultType="int">
SELECT COUNT(r_id)
FROM b_review;
</select>
Please help
I tried changing the XML resultType to Integer and the return type to Integer, but it didn't work.

Related

Spring boot and BigDecimal or Double serialization problem

İ can not handle BigDecimal initialization properly , i have an entity which has a BigDecimal field like this:
#Entity
public class Menu{
...
#Digits(integer=6, fraction=2)
private BigDecimal price;
...
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
...
other generated getters and setters toString etc.
...
}
And in frontend i use thymeleaf, in html form (which adds and updates new menu item) i have this input for Big Decimal value:
<div class="form-group">
<label for="price">Enter Price</label>
<input type="number" class="form-control" step="0.01" id="price" name="price" th:field="*{price}" placeholder="enter Price" value=" ">
</div>
And for restrict the user to enter more than 2 digit precision on price value, i have a js code like this:
$('#price').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
e.preventDefault();
return false;
}
});
The question is : when user enters 10.25 value in the form , thymeleaf renders it like 10.2499998.. . Even other rest endpoints returns this entity with value in json like 10.249999. But when i looked at my database (postgresql and offcourse i use jpa) this value seems just fine which is 10.25.
So i know when initializing new BigDecimal value the constructor must be like new BigDecimal("10.25") with string in parameter.But all i have is the default getters and setters and my controller is simple post controller for entity saving like this:
#PostMapping("/additem")
public String addItemPost(#ModelAttribute(value="menu") #Valid Menu menu,Model model,BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "addmenuitem";
}
this.menuService.saveMenuItem(menu);
return "redirect:/restaurant/menu";
}
The problem 2 is : I tried to change BigDecimal with Double value and after that, the input form takes value as we suggest and i see that value everywhere correctly.But if i write more digit after comma , the js function blocks me to write more than 2 digit but real value again becomes 10.2499999.. .
It must be something with spring's strategy of taking values from thymeleaf form, and than initialize those values into entity , but i never do that manually neighter couldn't debug it.
So ı don't know the problem is if my javascript function or my input form or the variable type.Please help.
Any help will be appreciated.
I found the problem and writing here if anyone encounter a problem like this.
My Problem was not in localhost , but occured on heroku.So i realized that in heroku postgresql db my BigDecimal columns did not updated and in localhost they were changing whenever i re-run because of jdbc table creation strategy choice.
I made the entity attribute Double and changed remote db columns to double precision than problem solved.

MyBatis foreach: there is no getter for property error

I'm getting 'there is no getter for property' error while executing foreach loop in mybatis. From the form I am gettin an array of strings (hashtag). In my PostInfoVO, I have a list of string like this:
private List<String> hashtags;
and its getters and setters like this:
public List<String> getHashtags() {
return hashtags;
}
public void setHashtags(List<String> hashtags) {
if (this.items == null)
this.items = new ArrayList<String>();
}
I checked that the list of hashtags is passing data to cotroller by logging postvo.getHashtags().toString().
In my MyBatis file, I have the following foreach loop which is returning 'there is no getter for property hashtag in PostInfoVO.
<![CDATA[
BEGIN
<foreach collection="hashtags" item="hashtag" separator=",">
INSERT INTO TBL_HASHTAG_INFO(post_id, hashtag)
VALUES
((SELECT post_id FROM TBL_POST_INFO ORDER BY post_id DESC LIMIT 1), #{hashtag})
</foreach>;
]]>
END;
List of things I tried:
Removing Begin and end
Taking Insert statement out of foreach loop
Open="(", Close=")"
Any advice would be appreciated! Thank you so much.
There are two problems in your code : your field name is hashtags but you used this.items in setter method and with this setter method you implemented the argument of setter method never assigns to the hashtags(field) ,Edit it as below :
public void setHashtags(List<String> hashtags) {
this.hashtags = hashtags;
}

Spring PagingAndSortingRepository returns all results instead of desired page size

I am using Spring Data JPA and I have a repository which extends PagingAndSortingRepository. My issue is that I have a query in which returns all of the results instead of the desired page size (100). I can't seem to find an issue that is wrong. Can anyone assist please?
#Test
public void testFindPageByStartAndEndDate() {
Timestamp endDate = Timestamp.valueOf("2017-06-14 09:18:42");
Timestamp startDate = Timestamp.valueOf("2017-05-19 01:31:23");
PageRequest pageRequest1 = new PageRequest(0, 100, Sort.Direction.ASC, "orderDate");
Page<Order> page1Orders = orderRepository.findPageByStartAndEndDate(startDate, endDate, pageRequest1);
assertThat(page1Orders.getTotalElements(), greaterThan(0L));
//
//
// Test Fails Here
// Expected: a value less than <101L>
// but: <139L> was greater than <101L>
//
//
assertThat(page1Orders.getTotalElements(), lessThan(101L));
}
This is the query that I am using.
#Query("SELECT o FROM Order o WHERE o.orderDate >= ?1 AND o.orderDate <= ?2")
Page<Order> findPageByStartAndEndDate(#Param("startDate") Timestamp startDate,
#Param("endDate") Timestamp endDate,
Pageable pageable);
getTotalElements() returns the count without pagination.
You get the number of elements present in the slice with getNumberOfElements().
See the implementation of Page as a reference here.

How to populate Form from Spring dropdown when form is submitted

My code lists the data that I would like to see, but when I hit submit it fails to populate the backing form with exception below. How can I make the bindings work? The exception I get is of Mismatch type, trying to insert a String in List when expecting Objects. Which makes sense.
Example
<tr>
<td><form:select id="myTypes" path="myTypes" multiple="false">
<form:option value="NONE" label="--- Select ---" />
<form:options items="${form.myTypes}" itemValue="id" itemLabel="label"/>
</form:select>
</td>
<td><form:errors path="myTypes" cssClass="error" /></td>
This is how form looks like
public class MyForm {
List<MyType> myTypes;
public List<MyType> getMyTypes() {
return myTypes;
}
public void setMyTypes(List<MyType> myTypes) {
this.myTypes = myTypes;
}
}
And of course MyType has id and label.
Link to above sample code and exception below
HTTP Status 500 - Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'Form' on field 'myTypes': rejected value [8768743658734587345]; codes [typeMismatch.Form.myTypes,typeMismatch.myTypes,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [myForm.myTypes,myTypes]; arguments []; default message [myTypes]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'myTypes'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.x.x.MyTypeEntity] for property 'myTypes[0]': no matching editors or conversion strategy found]
Solution:
Make sure you are mapping to Single element and not to the list :)
It should be something like
<form:select path="someEntity[${status.index}].myType.id">
HTH
I think the problem is that Spring does not know how to convert the selected option value (which is a String posted towards your app as an HTTP parameter named "myTypes" when you submit the form) to a MyType object. You should configure a Formatter< MyType > and register it to the Spring FormatterRegistry (see Spring doc) to let Spring know how to convert the incoming String to a MyType object.
public class MyTypeFormatter implements Formatter<MyType> {
#Override
public MyType parse(String text, Locale locale) throws ParseException {
return myTypeService.getType(text); // for example
}
public String print(MyType t, Locale locale) {
return t.getId();// for example
};
}
By the way, if I may, since your dropdown list is not multiple, it means that you are going to select just one of the available MyType options. The path of the < form:select > should be named "myType" instead of "myTypes" and especially, it should refer to a MyType attribute within your Form object and not to a List< MyType > attribute. Maybe you should name your first list of available MyType objects "availableTypes" and create a second attribute named "selectedType" to bind the MyType object corresponding to the selected option on the GUI.

How to use two java bean to display data in a jsp

I want to display user's detail in a jsp. user's email, name is in one bean. which i am getting in a PagedListHolder. now i need date too which is in another bean . how can i add this date to PagedListHolder. i am using spring mvc framework
public String listUsers(Map<String, Object> map, #RequestParam(value="p", required=false) Integer p) {
PagedListHolder pagedListHolder = new PagedListHolder(usersService.listUsers());
map.put("date11", userActivity.getLastSeen_time());
int page = p;
pagedListHolder.setPage(page);
int pageSize = 2;
pagedListHolder.setPageSize(pageSize);
map.put("pagedListHolder", pagedListHolder);
System.out.println(":::::::::");
return "userListView";
}
in jsp i am using it as
<c:forEach items="${pagedListHolder.pageList}" var="user">
<tr onmouseover="ChangeColor(this, true);" onmouseout="ChangeColor(this, false);" onclick="DoNav('${pageContext.request.contextPath}/secure/detailUserView');">
<td>${user.name}</td>
<td>${user.email}</td>
<td>`DATE`</td>
</tr>
</c:forEach>
in jsp in place of DATE i need to display date which is in date bean
If the pagedListHolder stored as "pagedListHolder" in the map is available using ${pagedListHolder}, then the date, stored as "date11" in the map, must also be available using ${date11}.
You can format it using <fmt:formatDate value="{date11}"/>.

Resources