BaseCrudRepository findById returns null when the record exists - spring

I've encountered a problem with spring where a call to the repository findById(id) returns null. The record in question exists in the postgresql database, and my call to return pages of records works correctly. This is implemented via Classes which extend BaseCrudService and BaseCrudRepository. In the case with the problem, the controller calls the BaseCrudService function directly. It is not overridden in the extended classes. I have implemented the same code for two similar classes and underlying tables and it works okay. I cannot find what is different with this one.
'id' in the table is a unique numeric.
Code in Controller which extends PageCrudController
#RestController
#RequestMapping(API_ENDPOINT)
public class WildlifeController extends PageCrudController<Wildlife, Long, WildlifeView> {
private static final Logger LOG = LoggerFactory.getLogger(WildlifeController.class);
private final WildlifeService service;
private final WildlifeValidation validation;
#Autowired
protected WildlifeController(final WildlifeMapper mapper, final WildlifeService service, final WildlifeValidation validation ) {
super(API_ENDPOINT, mapper, service);
this.service = service;
this.validation = validation;
}
#GetMapping
#PreAuthorize(HAS_AUTHORITY_READ)
public ResponseEntity<Page<WildlifePageView>> findPage(#SortDefault(sort = DEFAULT_SORT_FIELD) Pageable pageable ) {
LOG.debug("Find Wildlife by Pageable: {}", pageable);
// Return only results for authenticated user's aerodrome
Aerodrome aerodrome = Objects.requireNonNull(SecurityContext.getPrincipal()).getAerodrome();
Page<WildlifePageView> result = service.findPageByAerodrome(aerodrome, pageable, WildlifePageView.class);
return ResponseEntity.ok(result);
}
#GetMapping("/{id}")
#PreAuthorize(HAS_AUTHORITY_READ)
public ResponseEntity<WildlifeView> find(#PathVariable("id") Long id) {
LOG.debug("Find Wildlife by id: {}", id);
Wildlife result = service.find(id);
LOG.debug("Found Wildlife by id: {} = {}", id, result);
return Optional.ofNullable(result).map(this::responseOk)
.orElse(responseNotFound());
}
#PostMapping()
#PreAuthorize(HAS_AUTHORITY_WRITE)
public ResponseEntity<WildlifeView> create(#Valid #RequestBody WildlifeView view) {
LOG.debug("Create Wildlife by view: {}", view);
validation.validate(view);
return super.doCreate(view);
}
#PutMapping("/{id}")
#PreAuthorize(HAS_AUTHORITY_WRITE)
public ResponseEntity<WildlifeView> update(#PathVariable("id") Long id, #Valid #RequestBody WildlifeView view) {
LOG.debug("Update Wildlife '{}' by view: {}", id, view);
validation.validate(view);
return super.doUpdate(id, view);
}
#DeleteMapping("/{id}")
#PreAuthorize(HAS_AUTHORITY_WRITE)
public ResponseEntity<WildlifeView> delete(#PathVariable("id") Long id) {
LOG.debug("Delete Wildlife by ID: {}", id);
validation.validate(id);
return super.doDelete(id);
}
}
Code in BaseCrudService - I've added the debug statements.
#Transactional(readOnly = true)
public E find(final ID id) {
LOG.debug("Find with ID: {}", id);
LOG.debug("Find with ID: {} count {}", id, this.repository.count());
return repository.findById(id).orElse(null);
}

Found my problem. I had an an entity property marked nullable = false mapped to a nullable database table. The data set I was using had nulls in this column which prevents it from being read.
Broken:
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "cntrl_msrs_tkn_1_id", nullable = false)
private LutTabWlcm controlMeasuresTaken1;
Fixed
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "cntrl_msrs_tkn_1_id")
private LutTabWlcm controlMeasuresTaken1;

Related

Spring boot Restful API: DTO with relationships convert to entity using ModelMapper?

I'm now confused about how to do a CRUD in a Rest API with Spring.
Let me explain, I have two routes to POST and PUT an entity. I created two DTOs createPostRequest and updatePostRequest for this. Because when adding, the properties cannot be null, while when updating they can (nulled properties are ignored).
Problem 1:
On my frontend, the user is asked to choose a list of tags from the database (multi select html). This is why createPostRequest has a tags property typed TagDTO. But, how can I use modelMapper to map, for example, the createPostRequest to the Post entity making sure that the tags exist in the database?
if for example a user try to insert a tag that does not exist, I was thinking of doing something like this:
postEntity.setTags(tagService.findAllByIds(postEntity.getTagsId()));
This makes a lot of repetition in the code, because between create and update method of my entity in service, there is a lot of identical code.
Problem 2:
Based on my problem 1, how can I easily map my two DTOs to the same entity without repeating the code 2x?
Code example - PostService (see comment)
This is an example for the update, but there will be almost identical code for the create, so how do I proceed?
#Transactional
public Post update(Integer postId, UpdatePostRequest request) {
return Optional.ofNullable(this.getById(postId)).map(post -> {
// here how to map non-null properties of my request
// into my post taking in consideration my comment above?
postDAO.save(post);
return post;
}).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
}
================================
UPDATE:
As requested, found the code bellow.
The controller:
#RestController
#RequestMapping("/v1/posts")
public class PostController {
RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json; charset=UTF-8")
public ResponseEntity<Object> update(#Valid #RequestBody CreatePostRequest createPostRequest) {
Post post = postService.create(createPostRequest);
return new ApiResponseHandler(new PostDTO(post), HttpStatus.OK).response();
}
RequestMapping(value = "/{postId}", method = RequestMethod.PUT, consumes = "application/json", produces = "application/json; charset=UTF-8")
public ResponseEntity<Object> update(#Valid #RequestBody UpdatePostRequest updatePostRequest, #PathVariable Integer postId) {
Post post = postService.update(postId, updatePostRequest);
return new ApiResponseHandler(new PostDTO(post), HttpStatus.OK).response();
}
}
CreatePostRequest :
#Data
public class CreatePostRequest {
#NotNull
#Size(min = 10, max = 30)
private Sting title;
#NotNull
#Size(min = 50, max = 600)
private String description
#NotNull
#ValidDateString
private String expirationDate;
#NotNull
private List<TagDTO> tags;
public List<Integer> getTagIds() {
return this.getTags().stream().map(TagDTO::getId).collect(Collectors.toList());
}
}
UpdatePostRequest :
#Data
public class UpdatePostRequest {
#Size(min = 10, max = 30)
private Sting title;
#Size(min = 50, max = 600)
private String description
#ValidDateString
private String expirationDate;
private List<TagDTO> tags;
public List<Integer> getTagIds() {
return this.getTags().stream().map(TagDTO::getId).collect(Collectors.toList());
}
}
The service :
#Service
#Transactional
public class PostService {
#Transactional
public Post create(CreatePostRequest request) {
ModelMapper modelMapper = new ModelMapper();
Post post = modelMapper.map(request, Post.class);
// map will not work for tags : how to check that tags exists in database ?
return postDAO.save(post);
}
#Transactional
public Post update(Integer postId, UpdatePostRequest request) {
return Optional.ofNullable(this.getById(postId)).map(post -> {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setSkipNullEnabled(true);
modelMapper.map(request, post);
// map will not work for tags : how to check that tags exists in database ?
postDAO.save(post);
return post;
}).orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));
}
}
To avoid duplication of two similar DTOs you could use #Validated group validations. This allows you to actively set which validations are to be done on each property. You can read more about this in the following online resource https://www.baeldung.com/spring-valid-vs-validated. You would begin with the creation of two market interfaces:
interface OnCreate {}
interface OnUpdate {}
You can then use these marker interfaces with any constraint annotation in your common DTO:
#Data
public class CreateOrUpdatePostRequest {
#NotNull(groups = OnCreate.class)
#Size(min = 10, max = 30, groups = {OnCreate.class, OnUpdate.class})
private Sting title;
#NotNull(groups = OnCreate.class)
#Size(min = 50, max = 600, groups = {OnCreate.class, OnUpdate.class})
private String description
#NotNull(groups = OnCreate.class)
#ValidDateString(groups = {OnCreate.class, OnUpdate.class})
private String expirationDate;
#NotNull(groups = OnCreate.class)
private List<TagDTO> tags;
public List<Integer> getTagIds() {
return this.getTags().stream().map(TagDTO::getId).collect(Collectors.toList());
}
}
Finally, you just need to annotate your methods in the Controller accordingly:
#RestController
#RequestMapping("/v1/posts")
#Validated
public class PostController {
#RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json; charset=UTF-8")
public ResponseEntity<Object> update(#Validated(OnCreate.class) #RequestBody CreateOrUpdatePostRequest createPostRequest) {
Post post = postService.create(createPostRequest);
return new ApiResponseHandler(new PostDTO(post), HttpStatus.OK).response();
}
#RequestMapping(value = "/{postId}", method = RequestMethod.PUT, consumes = "application/json", produces = "application/json; charset=UTF-8")
public ResponseEntity<Object> update(#Validated(OnUpdate.class) #RequestBody CreateOrUpdatePostRequest updatePostRequest, #PathVariable Integer postId) {
Post post = postService.update(postId, updatePostRequest);
return new ApiResponseHandler(new PostDTO(post), HttpStatus.OK).response();
}
}
With this, you can have a single mapping function.
Still, keep in mind that using validation groups can easily become an anti-pattern given that we are mixing different concerns. With validation groups, the validated entity has to know the validation rules for all the use cases it is used in. Having said that, I usually avoid using validation groups unless it is really necessary.
Regarding tags I guess your only option is to query the database. The ones that do not exist you should create them (I guess), so something along the following lines:
List<Integer> tagsId = createOrUpdatePostRequest.getTagsId();
List<Tag> tags = tagService.findAllByIds(tagsId);
List<Integer> nonExistentTagsId = tagsId.stream().filter(id -> tags.stream().noneMatch(tag -> tag.getId().equals(id)));
if (!nonExistentTagsId.isEmpty()) {
// create Tags and add them to tags List
}

RestController: returning Resource<> makes FetchType.LAZY to behave as FetchType.EAGER

I am having below mappings as Company having 1:N relation with CompanyFunds
#Entity
public class Company{
#Id
private Integer companyId;
private String name;
#OneToMany(mappedBy = "company")
private List<CompanyFund> companyFunds;
}
#Entity
public class CompanyFunds{
#Id
private Integer fundId;
private String name;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "company_id")
private Company company;
}
I am using Spring-data-Jpa for my persistence layer and below are the controller and service methods:
//controller
#GetMapping(value = "/{companyId}")
public Resource<Company> find(#PathVariable Integer companyId) {
Resource<Company> companyResource = companyService.find(companyId);
return companyResource;
}
//service
public Resource<CompanyTypeOther> find(Integer companyId) {
Company company = companyRepository.findById(companyId);
return restResourceAssembler.toResource(company);
}
#Component
public class RestResourceAssembler implements ResourceAssembler<T, Resource<T>> {
private EntityLinks entityLinks;
public RestResourceAssembler(EntityLinks entityLinks) {
this.entityLinks = entityLinks;
}
#Override
public Resource<T> toResource(T entity) {
Resource<T> resource = new Resource<>(entity);
resource.add(entityLinks.linkToSingleResource(entity.getClass(), entity.getId()).withSelfRel());
return resource;
}
}
Now the weird thing is, until the return companyResource;(in controller) doesn't get executed, the companyResource contains null for companyFunds i.e the LAZY loading is working fine till that point. But the moment the return companyResource; executes, something goes inside the Spring and the Select statement for CompanyFund gets fired. I debugged the steps and below is the code(try block) responsible for this:
public class ServletInvocableHandlerMethod extends InvocableHandlerMethod {
......
public void invokeAndHandle(ServletWebRequest webRequest, ModelAndViewContainer mavContainer,
........other code
try {
this.returnValueHandlers.handleReturnValue(
returnValue, getReturnValueType(returnValue), mavContainer, webRequest);
}
catch (Exception ex) {
if (logger.isTraceEnabled()) {
logger.trace(formatErrorForReturnValue(returnValue), ex);
}
throw ex;
}
}
.....
}
There are no toString() declared in entities, also no getCompanyFund() called. Can't understand what Spring is doing with returnValue above, so that some getters(or something) are getting called.
One more thing I noticed is, this problem only occurs when the Resource<Company> is returned. If I return Company from the controller, nothing unexpected happens. Lazy loading works fine.
Since I want to lazy load the entity, a little fix/hack solved the problem for me(as of now).
#JsonIgnore
#OneToMany(mappedBy = "company")
private List<CompanyFund> companyFunds;
#JsonIgnore prevents LAZY loaded entity from being serialized. So I guess the jackson is the culprit here.
This is not a fix is my view but just a hack to do the thing. Still waiting someone from Spring team to reply.

Spring JPA: Locking parent row when inserting one to many child record

We have two tables that have a one to many relationship. When we insert multiple records into the child table across multiple threads (more specifically across multiple REST web requests) we are running into lost update issues due to a race condition.
What we need to be able to do is have JPA recognize that the entity has been updated elsewhere prior to inserting the child record. I've tried using the #Version annotation approach but that doesn't seem to do the trick as the update/insert (I guess...) is happening on another table. I tried adding a version timestamp column on the parent table that is updated on every update but that didn't seem to do the trick either.
I think what I actually need to do is get a reference to the EntityManager directly so that I can issue a lock() command on the record prior to calling save(). I'm just too new to Spring to know if
A) that is indeed the correct approach,
B) if there is a better/easier way to do what we are trying to accomplish, and
C) how to actually do that.
Also, I am aware of the #OneToMany annotation but that didn't seem to do anything.
I've truncated the code below for brevity and I also created a trimmed down version of the code that demonstrates the problem and will hopefully make it easier to see what I am trying to do. In the test if you change the thread pool number to 1 you can see the test pass.
Engagement class:
#Entity
public class Engagement implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#ElementCollection(fetch = EAGER)
private List<String> assignedUsers;
#Version
private Long version;
private LocalDateTime updatedOn;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getVersion(){return version;}
public void setVersion(Long version){this.version = version;}
public LocalDateTime getUpdatedOn(){
return updatedOn;
}
public void setUpdatedOn(LocalDateTime updatedOn) {
this.updatedOn = updatedOn;
}
public List<String> getAssignedUsers() {
return assignedUsers;
}
public void setAssignedUsers(List<String> assignedUsers) {
this.assignedUsers = assignedUsers;
}
public Engagement() {
}
}
User class:
public final class User {
private final String name;
private final String email;
private final String userId;
private final List<Engagement> engagements;
#ConstructorProperties({"roles", "name", "email", "userId", "engagements"})
User(String name, String email, String userId, List<Engagement> engagements) {
this.name = name;
this.email = email;
this.userId = userId;
this.engagements = engagements;
}
public static User.UserBuilder builder() {
return new User.UserBuilder();
}
public String getName() {
return this.name;
}
public String getEmail() {
return this.email;
}
public String getUserId() {
return this.userId;
}
public List<Engagement> getEngagements() {
return this.engagements;
}
public static final class UserBuilder {
private String name;
private String email;
private String userId;
private List<Engagement> engagements;
UserBuilder() {
}
public User.UserBuilder name(String name) {
this.name = name;
return this;
}
public User.UserBuilder email(String email) {
this.email = email;
return this;
}
public User.UserBuilder userId(String userId) {
this.userId = userId;
return this;
}
public User.UserBuilder engagements(List<Engagement> engagements) {
this.engagements = engagements;
return this;
}
public User build() {
return new User(this.name, this.email, this.userId, this.engagements);
}
public String toString() {
return "User.UserBuilder(name=" + this.name + ", email=" + this.email + ", userId=" + this.userId + ", engagements=" + this.engagements + ")";
}
}
}
Thread test:
#RunWith(SpringJUnit4ClassRunner.class)
#SpringBootTest
public class EngagementTest {
#Mock
UsersAuthService usersService;
#Autowired
EngagementsRepository engagementsRepository;
UsersAuthService authService;
#Before
public void init() {
MockitoAnnotations.initMocks(this);
authService = new UsersAuthServiceImpl(usersService, engagementsRepository);
}
#Test
public void addingMultipleUsersAtOnceSucceeds() throws InterruptedException {
Long engagementId = 1L;
String userId1 = "user1";
String userId2 = "user2";
String userId3 = "user3";
String userId4 = "user4";
String userId5 = "user5";
String auth = "asdf";
User adminUser = User.builder()
.userId("adminUser")
.email("user#user.com")
.name("Admin User")
.build();
Engagement engagement = new Engagement();
engagement.setAssignedUsers(new ArrayList<>());
engagement.getAssignedUsers().add(adminUser.getUserId());
engagementsRepository.save(engagement);
ExecutorService executorService = Executors.newFixedThreadPool(5);//change this to 1 to see the test pass
List<Callable<Engagement>> callableList = Arrays.asList(
addUserThread(engagementId, userId1, auth, adminUser),
addUserThread(engagementId, userId2, auth, adminUser),
addUserThread(engagementId, userId3, auth, adminUser),
addUserThread(engagementId, userId4, auth, adminUser),
addUserThread(engagementId, userId5, auth, adminUser));
executorService.invokeAll(callableList);
Engagement after = engagementsRepository.findById(engagementId);
assertEquals(6, after.getAssignedUsers().size());
}
private Callable<Engagement> addUserThread(Long engagementId, String userId1, String auth, User adminUser) {
return () -> authService.addUserTo(engagementId, userId1, auth, adminUser);
}
}
What's happening here is that you submit the callbacks for execution but never actually wait for their completion before checking the result. You need to use the List<Future<Engagement>> to actually wait for the results to complete before proceeding.
Something like this would do the trick:
executorService.invokeAll(callableList).forEach(it -> {
try {
it.get(500, TimeUnit.MILLISECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
e.printStackTrace();
}
});
Note that this is not a proper way to deal with the exception case but it causes the code to wait for completion. If you have that in place you see the threads properly rejecting some of the updates with an ObjectOptimisticLockingFailureException:
java.util.concurrent.ExecutionException: org.springframework.orm.ObjectOptimisticLockingFailureException: Object of class [com.example.racecondition.engagement.Engagement] with identifier [1]: optimistic locking failed; nested exception is org.hibernate.StaleObjectStateException: Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [com.example.racecondition.engagement.Engagement#1]
at java.util.concurrent.FutureTask.report(FutureTask.java:122)
at java.util.concurrent.FutureTask.get(FutureTask.java:206)
at com.example.racecondition.EngagementTest.lambda$0(EngagementTest.java:68)
at java.util.ArrayList.forEach(ArrayList.java:1257)
at com.example.racecondition.EngagementTest.addingMultipleUsersAtOnceSucceeds(EngagementTest.java:66)
What's weird about the test case beyond that is that UsersAuthServiceImpl carries an #Transactional but the test case manually instantiates that class, so that there's no transactional proxy in place already. This causes the calls to findById(…) and save(…) from within addToUser(…) to run in two transactions. Tweaking that doesn't change the output though.
I think what I actually need to do is get a reference to the EntityManager directly so that I can issue a lock() command on the record prior to calling save(). I'm just too new to Spring to know if
A) that is indeed the correct approach,
If I understand you correctly you want to basically force a version increment on an entity so that if multiple threads do that one fails.
You can indeed achieve that by locking the entity in question using LockModeType.PESSIMISTIC_FORCE_INCREMENT or LockModeType.OPTIMISTIC_FORCE_INCREMENT.
B) if there is a better/easier way to do what we are trying to accomplish, and
C) how to actually do that.
With Spring Data probably the best way to do that is using the #Lock annotation on the method you use to load the entity.

Error with JPA PagingAndSorting request parameter

I have a Controller that pages and sorts all the news in my database:
#RequestMapping(value = "/viewstatus", method = RequestMethod.GET)
ModelAndView viewStatus(ModelAndView modelAndView, #RequestParam(name = "p", defaultValue = "1") int pageNumber) {
Page<StatusUpdate> page = statusUpdateService.getPage(pageNumber);
modelAndView.getModel().put("page", page);
modelAndView.setViewName("app.viewStatus");
return modelAndView;
}
With its call to the service that works fine:
public Page<StatusUpdate> getPage(int pageNumber) {
PageRequest request = new PageRequest(pageNumber-1, pageSize, Sort.Direction.DESC, "added");
return statusUpdateDao.findAll(request);
}
But now, I would like to do the same SortingAndPaging BUT with one parameter (SiteUser). Here is my object:
#Entity
#Table(name = "status_update")
public class StatusUpdate {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Size(min=5, max=255, message="{addstatus.title.size}")
#Column(name = "title")
private String title;
#Size(min=5, max=5000, message="{addstatus.text.size}")
#Column(name = "text")
private String text;
#Column(name = "added")
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(pattern="yyyy/MM/dd hh:mm:ss")
private Date added;
#OneToOne(targetEntity = SiteUser.class)
#JoinColumn(name="user_id")
private SiteUser siteUser;
#PrePersist
protected void onCreate() {
if (added == null) {
added = new Date();
}
}
public StatusUpdate() {
}
But when I do it, it gives me this error:
Exception: org.springframework.dao.InvalidDataAccessApiUsageException: Parameter value [3] did not match expected type [com.caveofprogramming.model.entity.SiteUser (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [3] did not match expected type [com.caveofprogramming.model.entity.SiteUser (n/a)]
Failed URL: http://192.168.160.128:8080/viewmystatus
Exception message: Parameter value [3] did not match expected type [com.caveofprogramming.model.entity.SiteUser (n/a)]; nested exception is java.lang.IllegalArgumentException: Parameter value [3] did not match expected type [com.caveofprogramming.model.entity.SiteUser (n/a)]
I tired to send a String, but it did not work. I had to change it to a NativeQuery but I does not work with PagingAndSorting, it only works as a List (which is a headache to work with). So if you can help me with the ERROR of PagingAndSorting that would be great.
Here is the Controller:
#RequestMapping(value = "/viewmystatus", method = RequestMethod.GET)
ModelAndView viewMyStatus(ModelAndView modelAndView, #RequestParam(name = "p", defaultValue = "1") int pageNumber) {
SiteUser user = getUser();
Long user_id= user.getId();
Page<StatusUpdate> page = statusUpdateService.findMyStatusUpdates(user_id, pageNumber);
for(StatusUpdate statusUpdate: page){
SiteUser siteUser= statusUpdate.getSiteUser();
modelAndView.getModel().put("siteuser", siteUser);
}
modelAndView.getModel().put("page", page);
modelAndView.setViewName("app.viewStatus");
return modelAndView;
}
Here is the service:
public Page<StatusUpdate> findMyStatusUpdates(Long user_id, int pageNumber) {
PageRequest request = new PageRequest(pageNumber-1, pageSize, Sort.Direction.DESC, "added");
return statusUpdateDao.findBySiteUser(user_id, request);
}
And the DAO:
#Repository
public interface StatusUpdateDao extends PagingAndSortingRepository<StatusUpdate, Long> {
StatusUpdate findFirstByOrderByAddedDesc();
Page<StatusUpdate> findBySiteUser(Long user_id, Pageable pageable);
}
Thanks for your help!
Use a SiteUser object:
public Page<StatusUpdate> findMyStatusUpdates(Long user_id, int pageNumber) {
PageRequest request = new PageRequest(pageNumber-1, pageSize, Sort.Direction.DESC, "added");
return statusUpdateDao.findBySiteUser(new SiteUser(user_id), request);
}
You could try query by nested properties as well, but I think you must change user_id by userId, as underscore is a reserved character. Have a look to the documentation:
Spring data JPA Property expressions
Have you changed your findBySiteUser method? The one you posted looks fine but it seems is complaining about the signature. Even when PageRequest implements Pageable the signature has to be declared, explicitly, using Pageable, but the error message you are getting says PageRequest
public abstract org.springframework.data.domain.Page com.caveofprogramming.model.repository.StatusUpdateDao.findB‌​ySiteUser(com.caveof‌​programming.model.en‌​tity.SiteUser,org.sp‌​ringframework.data.d‌​omain.PageRequest)
More info:
PageRequest parameter not recognized as Pageable in Paging query

How to return a list of object as Json in Spring MVC

I'm trying to get a list of objects to render on a Spring 3 MVC app and would like to do this via Ajax.
So in my Spring class I have:
#RequestMapping(value = "/viewSearchEnquiriesAjax", method = RequestMethod.GET, headers = "Accept=application/json")
public #ResponseBody List<Enquiry> getEnquiriesBySearchAjax(#RequestParam String name) {
Search search = new Search();
search.setFirstName(name);
return searchEnquiries(search);
}
But I get a 500 (Internal Server Error) when this is run. This manifests itself when I'm debugging in the browser as 'GET http://localhost:8080/SpringMVC/viewSearchEnquiriesAjax?name=peter 500 (Internal Server Error)'
I can successfully return a single object with no error. Can the Spring Json mapper(Jackson) convert correctly? Am I missing something fundamental?
My javascript is as follows:
function doAjaxPost() {
// get the form values
var firstName = $('#firstName').val();
$.getJSON("/SpringMVC/viewSearchEnquiriesAjax", { name: firstName }, function(result) {
alert("Success");
});
}
My Enquiry object is an Entity:
#Entity
#Table(name = "enquiries")
public class Enquiry implements java.io.Serializable{
private static final long serialVersionUID = -5093725544297637792L;
protected Long id;
protected Date created = new Date();
...
...
public Enquiry() {
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
...
...
For Jackson you have to create a strongly typed list class because of type erasure:
public class EnquiryList extends ArrayList<Enquiry> {
}
Then return this list from your controller:
#RequestMapping(value = "/viewSearchEnquiriesAjax", method = RequestMethod.GET, headers = "Accept=application/json")
public #ResponseBody EnquiryList getEnquiriesBySearchAjax(#RequestParam String name) {
EnquiryList list = new EnquiryList();
...
return list;
}
Also check out this answer on a similar question.

Resources