how can i solve mapper null pointer error in dao with spring - spring

[First, I was built bean for mapper interface and dao in Dispatcher Servlet.xml .Then I built the new package for mapper then add interface and i built dao too.In dao, i built service from dao bean in dispatcher servlet and mapper too.In Controller,Autowired DAO and qualified mapper but still don't know about the mapper
package Controller;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import DAO.CourseStudentDAO;
import DAO.CourseDAO;
import DAO.StudentDAO;
import DTO.CourseResponseDTO;
import DTO.CourseStudentRequestDTO;
import DTO.StudentRequestDTO;
import DTO.StudentResponseDTO;
import Model.StudentBean;
#Controller
public class StudentController
{
#Autowired
#Qualifier("sqlSession")
SqlSession session;
#Autowired
#Qualifier("courseStudentDAO")
private CourseStudentDAO CourseStudentDAO;
#Autowired
#Qualifier("courseDAO")
private CourseDAO CourseDAO;
#Autowired
#Qualifier("studentDAO")
private StudentDAO StudentDAO;
#RequestMapping(value="/studentaddpage",method=RequestMethod.GET)
public ModelAndView studentaddpage(ModelMap model)
{
CourseDAO.selectAll();
List<CourseResponseDTO> courseList = CourseDAO.selectAll();
model.addAttribute("courseList", courseList);
return new ModelAndView("STU001", "studentbean", new StudentBean());
}
#RequestMapping(value = "/StudentAddPage", method = RequestMethod.POST)
public String addStu(#ModelAttribute("studentbean") #Validated StudentBean studentbean, ModelMap model) {
//insert
List<String> attendArray = studentbean.getCourse();
if (studentbean.getStudentname().isBlank() || studentbean.getDob().isBlank() || studentbean.getGender().isBlank()||studentbean.getPhone().isBlank() ||studentbean.getEducation().isBlank() ||studentbean.getStudentid().isBlank())
{
model.addAttribute("errorFill", "Fill the Blank!!!");
return "redirect:/studentaddpage";
}else {
StudentDAO dao = new StudentDAO();
StudentResponseDTO res = new StudentResponseDTO();
StudentRequestDTO dto = new StudentRequestDTO();
DAO.CourseStudentDAO csdao = new DAO.CourseStudentDAO();
CourseStudentRequestDTO csdto = new CourseStudentRequestDTO();
for(String a : attendArray )
{ csdto.setStudentid(studentbean.getStudentid());
csdto.setCourse(a); csdao.insert(csdto); }
dto.setStudentid(studentbean.getStudentid());
dto.setStudentname(studentbean.getStudentname());
dto.setDob(studentbean.getDob());
dto.setGender(studentbean.getGender());
dto.setPhone(studentbean.getPhone());
dto.setEducation(studentbean.getEducation());
dao.insert(dto);
session.commit();
return "redirect:/studentsearchpage";
}
}
//show&search
#RequestMapping(value = "/studentsearchpage", method = RequestMethod.GET)
public ModelAndView stuSearchPage(ModelMap model)
{
StudentDAO dao = new StudentDAO();
CourseStudentDAO csdao = new CourseStudentDAO();
List<StudentResponseDTO> list = dao.selectAll();
for(StudentResponseDTO a : list) {
List<String> courselist = csdao.selectOne(a.getStudentid());
a.setCourse(courselist);
}
model.addAttribute("studentList", list);
return new ModelAndView("STU003", "studentbean", new StudentBean());
}
#RequestMapping(value = "/StudentSearchPage", method = RequestMethod.POST)
public ModelAndView searchStudent(#ModelAttribute("studentbean") StudentBean studentbean, ModelMap model)
{
StudentRequestDTO req = new StudentRequestDTO();
req.setStudentid(studentbean.getSearchid());
req.setStudentname(studentbean.getSearchname());
CourseStudentDAO csdao = new CourseStudentDAO();
StudentDAO dao = new StudentDAO();
if(dao.search(req).isEmpty()) {
return new ModelAndView("STU003", "studentbean", new StudentBean());
}
else {
List<StudentResponseDTO> list = dao.search(req);
for(StudentResponseDTO a : list) {
List<String> courselist = csdao.selectOne(a.getStudentid());
a.setCourse(courselist);
}
model.addAttribute("studentList", list);
List<StudentResponseDTO> dto=dao.search(req);
return new ModelAndView("STU003", "studentbean", new StudentBean());
}
}
//Student Update
#RequestMapping(value="/studentupdatedpage/{studentid}" ,method=RequestMethod.GET)
public ModelAndView studentupdatepage(#PathVariable String studentid,ModelMap model)
{
StudentRequestDTO dto=new StudentRequestDTO();
dto.setStudentid(studentid);
CourseDAO.selectAll();
List<CourseResponseDTO> courseList = CourseDAO.selectAll();
model.addAttribute("courseList", courseList);
return new ModelAndView("STU002","studentbean",StudentDAO.selectOne(dto));
}
#RequestMapping(value = "/studentupdatedpage/UpdateStudentUpdatePage" , method = RequestMethod.POST)
public String updateStu(#ModelAttribute("studentbean")StudentBean studentbean,ModelMap model) {
List<String> attendArray = studentbean.getCourse();
if (studentbean.getStudentname().isBlank() || studentbean.getDob().isBlank() || studentbean.getGender().isBlank()||studentbean.getPhone().isBlank() ||studentbean.getEducation().isBlank() ||studentbean.getStudentid().isBlank() ) {
model.addAttribute("errorFill", "Fill the Blank!!!");
model.addAttribute("studentbean", studentbean);
return "redirect:/studentupdatedpage";
} else {
StudentResponseDTO res = new StudentResponseDTO();
StudentRequestDTO dto = new StudentRequestDTO();
StudentDAO dao=new StudentDAO();
CourseStudentDAO csdao = new CourseStudentDAO();
CourseStudentRequestDTO csdto = new CourseStudentRequestDTO();
csdto.setStudentid(studentbean.getStudentid());
csdao.delete(csdto);
for(String a : attendArray ) {
csdto.setStudentid(studentbean.getStudentid());
csdto.setCourse(a);
csdao.insert(csdto);
}
dto.setStudentid(studentbean.getStudentid());
dto.setStudentname(studentbean.getStudentname());
dto.setDob(studentbean.getDob());
dto.setGender(studentbean.getGender());
dto.setPhone(studentbean.getPhone());
dto.setEducation(studentbean.getEducation());
dao.update(dto);
return "redirect:/studentsearchpage";
}
}
#RequestMapping(value = "/DeleteStudent/{studentid}", method = RequestMethod.GET)
public String deleteStu(#PathVariable String studentid, ModelMap model) {
StudentDAO dao=new StudentDAO();
StudentRequestDTO dto = new StudentRequestDTO();
CourseStudentDAO csdao = new CourseStudentDAO();
CourseStudentRequestDTO csdto = new CourseStudentRequestDTO();
dto.setStudentid(studentid);
csdto.setStudentid(studentid);
dao.delete(dto);
csdao.delete(csdto);
model.addAttribute("errorFill", "Success delete");
return "redirect:/stuSearchPage";
}
}
]1

Related

404 error with Postman while trying to test springboot code

I was following a tutorial to save and retrieve images from database using spring boot and angular.
I was trying to test it with Postman, putting an image in the db but getting the 404 error.
Below is the picture of postman
Can anyone explain to me what it is due to? thank you all
ImageModel.java
package com.javainuse.model;
import javax.persistence.*;
#Entity
#Table(name = "image_table")
public class ImageModel {
public ImageModel() {
super();
}
public ImageModel(String name, String type, byte[] picByte) {
this.name = name;
this.type = type;
this.picByte = picByte;
}
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "name")
private String name;
#Column(name = "type")
private String type;
//image bytes can have large lengths so we specify a value
//which is more than the default length for picByte column
#Column(name = "picByte", length = 1000)
private byte[] picByte;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public byte[] getPicByte() {
return picByte;
}
public void setPicByte(byte[] picByte) {
this.picByte = picByte;
}
}
ImageRepository.java
package com.javainuse.db;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import com.javainuse.model.ImageModel;
public interface ImageRepository extends JpaRepository<ImageModel, Long> {
Optional<ImageModel> findByName(String name);
}
ImageUploadController
package com.javainuse.controller;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Optional;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.javainuse.db.ImageRepository;
import com.javainuse.model.ImageModel;
#RestController
#CrossOrigin(origins = "http://localhost:4200")
#RequestMapping(path = "image")
public class ImageUploadController {
#Autowired
ImageRepository imageRepository;
#PostMapping("/upload")
public BodyBuilder uplaodImage(#RequestParam("imageFile") MultipartFile file) throws IOException {
System.out.println("Original Image Byte Size - " + file.getBytes().length);
ImageModel img = new ImageModel(file.getOriginalFilename(), file.getContentType(),
compressBytes(file.getBytes()));
imageRepository.save(img);
return ResponseEntity.status(HttpStatus.OK);
}
#GetMapping(path = { "/get/{imageName}" })
public ImageModel getImage(#PathVariable("imageName") String imageName) throws IOException {
final Optional<ImageModel> retrievedImage = imageRepository.findByName(imageName);
ImageModel img = new ImageModel(retrievedImage.get().getName(), retrievedImage.get().getType(),
decompressBytes(retrievedImage.get().getPicByte()));
return img;
}
// compress the image bytes before storing it in the database
public static byte[] compressBytes(byte[] data) {
Deflater deflater = new Deflater();
deflater.setInput(data);
deflater.finish();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int count = deflater.deflate(buffer);
outputStream.write(buffer, 0, count);
}
try {
outputStream.close();
} catch (IOException e) {
}
System.out.println("Compressed Image Byte Size - " + outputStream.toByteArray().length);
return outputStream.toByteArray();
}
// uncompress the image bytes before returning it to the angular application
public static byte[] decompressBytes(byte[] data) {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
try {
while (!inflater.finished()) {
int count = inflater.inflate(buffer);
outputStream.write(buffer, 0, count);
}
outputStream.close();
} catch (IOException ioe) {
} catch (DataFormatException e) {
}
return outputStream.toByteArray();
}
}
Postman error
postman error
Hi elfuso please add path slash example
#RequestMapping(path = "/image")

GSON deserializing null value not working

I am trying to de-serialize the json string. I tried different API's but I didn't find the solution. Here, am trying to deserialize below json and want to read value of each field/element. Example below -
String inputJson = "{"phone":null, "address":"underworld"}";
LinkedTreeMap map = new Gson().fromJson(inputJson , LinkedTreeMap.class);
When I say map.containsKey("phone), it is giving as false, it means "phone" element is not present in the json string. But, this is not correct as we could see that this element is present in the input json.
Can anyone help me on any API which can give keys with value as well.
With spring boot what is the correct jackson deserialization configuration which can accept null values? Currently I am using like below -
pubic ObjectMapper objectMapper(Jckson3OjectMapperBuilder builder) {
ObjectMapper mapper = builder.build();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return mapper;
}
I've written some tests that deserialize and serialize your cases maybe this will help you
GSON always deserializes null object if you want to change, write your adapter
I use JDK1.8 and com.google.code.gson:gson:2.8.6
package pl.jac.mija.gson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.internal.LinkedTreeMap;
import com.google.gson.internal.bind.ObjectTypeAdapter;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import org.junit.Test;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class GsonWithNullTest {
#Test
public void deserializeWithNull() {
//given
String inputJson = "{\"phone\":null, \"address\":\"underworld\"}";
//when
LinkedTreeMap<String, Object> map = new Gson().fromJson(inputJson, LinkedTreeMap.class);
boolean phone = map.containsKey("phone");
//then
assertEquals(true, phone);
}
#Test
public void deserializeWithoutNull_V1_use_adapter() {
//given
String inputJson = "{\"phone\":null, \"address\":\"underworld\"}";
//when
Gson gson = new GsonBuilder().registerTypeAdapter(LinkedTreeMap.class, new MyAdapterSkipNull()).create();
LinkedTreeMap<String, Object> map = gson.fromJson(inputJson, LinkedTreeMap.class);
//then
boolean isPhone = map.containsKey("phone");
boolean isAddress = map.containsKey("address");
assertEquals(false, isPhone);
assertEquals(true, isAddress);
}
#Test
public void deserializeWithoutNull_V2_use_post_filter_null() {
//given
String inputJson = "{\"phone\":null, \"address\":\"underworld\"}";
//when
Gson gson = new GsonBuilder().registerTypeAdapter(LinkedTreeMap.class, new MyAdapterSkipNull()).create();
LinkedTreeMap<String, Object> map = new Gson().fromJson(inputJson, LinkedTreeMap.class);
Map<String, Object> collect = map.entrySet().stream().filter(x -> x.getValue() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
//then
boolean isPhone = collect.containsKey("phone");
boolean isAddress = collect.containsKey("address");
assertEquals(false, isPhone);
assertEquals(true, isAddress);
}
#Test
public void serializeWithoutNull() {
//given
Map<String, Object> map = new HashMap<>();
map.put("phone", null);
map.put("address", "underworld");
//when
Gson gson = new GsonBuilder().serializeNulls().create();
String json = gson.toJson(map);
//then
List<String> answert = new ArrayList<>();
answert.add("{\"address\":\"underworld\",\"phone\":null}");
answert.add("{\"phone\":null,\"address\":\"underworld\"}");
assertTrue(answert.contains(json));
}
#Test
public void serializeWithNull() {
//given
Map<String, Object> map = new HashMap<>();
map.put("phone", null);
map.put("address", "underworld");
//when
Gson gson = new Gson();
String json = gson.toJson(map);
//then
assertEquals("{\"address\":\"underworld\"}", json);
}
}
class MyAdapterSkipNull extends TypeAdapter<LinkedTreeMap<String, Object>> {
#Override
public void write(JsonWriter out, LinkedTreeMap<String, Object> value) throws IOException {
throw new NotImplementedException();
}
#Override
public LinkedTreeMap<String, Object> read(JsonReader in) throws IOException {
JsonToken peek = in.peek();
if (peek == JsonToken.NULL) {
in.nextNull();
return null;
}
TypeAdapter<Object> objectTypeAdapter = ObjectTypeAdapter.FACTORY.create(new Gson(), TypeToken.get(Object.class));
LinkedTreeMap<String, Object> map = new LinkedTreeMap<>();
in.beginObject();
while (in.hasNext()) {
String key = in.nextName();
JsonToken peek1 = in.peek();
if (JsonToken.NULL.equals(peek1)) {
in.skipValue(); //skip NULL
} else {
Object read = objectTypeAdapter.read(in);
map.put(key, read);
}
}
in.endObject();
return map;
}
}
I have solved this problem by changing spring boot end point method argument signature from Object to String. Earlier it was Object type because of that it just ignoring keys having null values in the String. And in the controller I am checking the existence of the key as below -
public ResponseEntity<Object> validate(#RequestBody String requestBody) {
Object requestObject = new ObjectMapper().readValue(requestBody, Object.class);
LinkedTreeMap requestObjectMap = new Gson().fromJson(requestObject.toString(), LinkedTreeMap.class);
List<FieldError> fieldErrors = new ArrayList<>();
final boolean isKeyExists = requestObjectMap.containsKey("keyname");
final Object fieldValue = requestObjectMap.get(optionalField);
if (isKeyExists && (Objects.isNull(fieldValue)) {
System.out.println("Key exists but its value is null in the input Json request");
}
// other logic
}

Get _links with spring RepositoryRestController

I have defined custom controllers for my repositories. For example, one looks like this
#RequestMapping(method = RequestMethod.GET, value = "/myEntities")
public ResponseEntity<?> get() {
...TO SOME STUFF
MyEntity myEntity= myEntityRepository.findById(1);
return ResponseEntity.ok(new Resource<>(myEntity));
}
This returns a JSON format data which includes a _links section, where I can get the href to the entity.
Now if I want to return an array of entities which are all resources, I get stuck.
What I have tried so far:
1.
#RequestMapping(method = RequestMethod.GET, value = "/myEntities")
public ResponseEntity<?> get() {
...TO SOME STUFF
List<MyEntity> myEntityList= myEntityRepository.findAll(1);
return ResponseEntity.ok(new Resources<>(myEntityList));
}
2.
#RequestMapping(method = RequestMethod.GET, value = "/myEntities")
public ResponseEntity<?> get() {
...TO SOME STUFF
List<MyEntity> myEntityList= myEntityRepository.findAll();
List<Resource<MyEntity>> resources = new ArrayList<>();
myEntityList.forEach(me -> {
resources.add(new Resource<>(me));
})
return ResponseEntity.ok(resources);
}
Option 1. and 2. don't add _links to the result and I don't understand why. I have googled it a lot and you can add links manually but this seems to be a much clearer way. Can anybody understand, what I'm doing wrong?
There are answers at "adding association links to spring data rest custom exposed method" and "Enable HAL serialization in Spring Boot for custom controller method" for similar questions. I tried something a little different from those answers, for solving a similar situation, and it worked fine. I wish you get your problem solved.
It follows how I did solve my specific situation:
#PostMapping(value = "/myEntities/searchWithParams"
, consumes = MediaType.APPLICATION_JSON_VALUE
, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> searchWithParams(#RequestBody SearchParamsDtoClass params, PersistentEntityResourceAssembler assembler)
{
List<MyEntity> entities = myEntityService.searchWithParams(params);
List<PersistentEntityResource> resourcesList = new ArrayList<PersistentEntityResource>();
for (MyEntity entity: entities) {
PersistentEntityResource resource = assembler.toResource(entity);
resourcesList.add(resource);
}
Resources<PersistentEntityResource> resources = new Resources(resourcesList);
return ResponseEntity.ok(resources);
}
The Resources constructor accepts a collection of embedded content, which is not the same as a collection of links. You have to add the links manually.
Resources resources = new Resources();
resources.add(myEntityRepository
.findAll()
.stream()
.map(entry -> convertToLink(entry)
.collect(Collectors.toList()));
return ResponseEntity.ok(resources);
Here is an example that includes embedded content and pagination in a HAL compliant format.
import static java.util.Objects.*;
import static java.util.Optional.*;
import static org.elasticsearch.index.query.QueryBuilders.*;
import static org.springframework.hateoas.MediaTypes.*;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*;
import static org.springframework.http.HttpStatus.*;
import static org.springframework.http.MediaType.*;
import static org.springframework.web.bind.annotation.RequestMethod.*;
import java.util.ArrayList;
import javax.inject.Inject;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.elasticsearch.index.query.QueryBuilder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.hateoas.Link;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.codahale.metrics.annotation.Timed;
#RestController
#RequestMapping("/catalog/users")
public class UserResource {
private final #NotNull UserLocator locator;
private final #NotNull ElasticsearchOperations elasticsearchTemplate;
#Inject
public UserResource(
final #NotNull UserLocator locator,
final #NotNull ElasticsearchOperations elasticsearchTemplate
) {
this.locator = requireNonNull(locator, "locator cannot be null");
this.elasticsearchTemplate = requireNonNull(elasticsearchTemplate, "elasticsearchTemplate cannot be null");
}
/**
* GET /users : get all the users.
*
* #return the ResponseEntity with status 200 (OK) and the list of users in body
*/
#Timed
#RequestMapping(method = GET, produces = { HAL_JSON_VALUE, APPLICATION_JSON_VALUE })
public ResponseEntity<Representations<User>> allUsers(
#RequestParam(name = "page", required = false, defaultValue = "0") #Min(0) int page,
#RequestParam(name = "size", required = false, defaultValue = "25") #Min(1) int size,
#RequestParam(name = "like", required = false) String like
) {
final PageRequest pageRequest = new PageRequest(page, size, Sort.Direction.ASC, "surname.raw", "givenName.raw");
final Page<User> entries = elasticsearchTemplate.queryForPage(
new NativeSearchQueryBuilder()
.withQuery(startingWith(like))
.withPageable(pageRequest)
.build(),
User.class
);
final ArrayList<Link> links = new ArrayList<>();
links.add(linkTo(UserResource.class).withSelfRel());
if (!entries.isFirst()) {
links.add(linkTo(methodOn(UserResource.class).allUsers(0, size, like)).withRel("first"));
}
if (!entries.isLast()) {
links.add(linkTo(methodOn(UserResource.class).allUsers(entries.getTotalPages() - 1, size, like)).withRel("last"));
}
if (entries.hasNext()) {
links.add(linkTo(methodOn(UserResource.class).allUsers(entries.nextPageable().getPageNumber(), size, like)).withRel("next"));
}
if (entries.hasPrevious()) {
links.add(linkTo(methodOn(UserResource.class).allUsers(entries.previousPageable().getPageNumber(), size, like)).withRel("prev"));
}
final Representations<User> resourceList = new Representations<>(entries, Representations.extractMetadata(entries), links);
return ResponseEntity.ok(resourceList);
}
private QueryBuilder startingWith(String like) {
return isNull(like) ? null : matchPhrasePrefixQuery("_all", like);
}
/**
* GET /users/:identifier : get the "identifier" user.
*
* #param identifier the identifier of the role to retrieve
* #return the ResponseEntity with status 200 (OK) and with body the role, or with status 404 (Not Found) or with 410 (Gone)
*/
#Timed
#RequestMapping(value = "/{identifier}", method = GET, produces = APPLICATION_JSON_VALUE)
public ResponseEntity<UserRepresentation> aUser(
#PathVariable("identifier") #NotNull String identifier
) {
return ofNullable(this.locator.findOne(identifier))
.map(user -> toRepresentation(user))
.map(ResponseEntity::ok)
.orElse(notFound())
;
}
private #NotNull UserRepresentation toRepresentation(final #NotNull User role) {
final String id = role.getIdentifier();
final Link self = linkTo(methodOn(UserResource.class).aUser(id)).withSelfRel().expand(id);
final Link collection = linkTo(UserResource.class).withRel("collection");
return new UserRepresentation(role, self, collection);
}
protected final #NotNull <U> ResponseEntity<U> notFound() {
return new ResponseEntity<>(NOT_FOUND);
}
}
import java.util.Optional;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.core.Relation;
#Relation(value = "item", collectionRelation = "items")
public class UserRepresentation extends Representation<User> {
public UserRepresentation(User content, Iterable<Optional<Link>> links) {
super(content, links);
}
public UserRepresentation(User content, Link... links) {
super(content, links);
}
#SafeVarargs
public UserRepresentation(User content, Optional<Link>... links) {
super(content, links);
}
public UserRepresentation(User content) {
super(content);
}
}
import static java.util.Arrays.*;
import static java.util.Collections.*;
import static java.util.Objects.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.ResourceSupport;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Representation<T> extends Resource<T> {
private final Map<String, ResourceSupport> embedded = new HashMap<>();
public Representation(final #NotNull T content) {
super(content, emptyList());
}
public Representation(final #NotNull T content, final #NotNull Link... links) {
super(content, links);
}
#SafeVarargs
public Representation(final #NotNull T content, final #NotNull Optional<Link>... links) {
this(content, (Iterable<Optional<Link>>) asList(links));
}
public Representation(final #NotNull T content, final #NotNull Iterable<Optional<Link>> links) {
super(content, emptyList());
asStream(links).forEach(this::add);
}
public void add(final #NotNull Optional<Link> link) {
if (null != link && link.isPresent()) super.add(link.get());
}
#JsonProperty("_embedded")
#JsonInclude(Include.NON_EMPTY)
public final #NotNull Map<String, ResourceSupport> getEmbedded() {
return this.embedded;
}
/**
* #param rel must not be {#literal null} or empty.
* #param resource the resource to embed
*/
public final void embed(final #NotNull #Size(min=1) String rel, final ResourceSupport resource) {
requireNonNull(rel, "rel cannot be null");
if (rel.trim().isEmpty()) {
throw new IllegalArgumentException("rel cannot be empty");
}
if (null != resource) {
this.embedded.put(rel, resource);
}
}
}
import javax.validation.constraints.NotNull;
import org.springframework.data.domain.Page;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.Resources;
import org.springframework.hateoas.PagedResources.PageMetadata;
import org.springframework.hateoas.core.Relation;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
#Relation(collectionRelation = "items")
public class Representations<T> extends Resources<T> {
#JsonUnwrapped
#JsonInclude(JsonInclude.Include.NON_NULL)
private final PageMetadata metadata;
public Representations(Iterable<T> content) {
super(content);
this.metadata = null;
}
public Representations(Iterable<T> content, PageMetadata metadata) {
super(content);
this.metadata = metadata;
}
public Representations(Iterable<T> content, Iterable<Link> links) {
super(content, links);
this.metadata = null;
}
public Representations(Iterable<T> content, PageMetadata metadata, Iterable<Link> links) {
super(content, links);
this.metadata = metadata;
}
public Representations(Iterable<T> content, Link... links) {
super(content, links);
this.metadata = null;
}
public Representations(Iterable<T> content, PageMetadata metadata, Link... links) {
super(content, links);
this.metadata = metadata;
}
/**
* Returns the pagination metadata.
*
* #return the metadata
*/
#JsonProperty("page")
public PageMetadata getMetadata() {
return metadata;
}
public static <U> PageMetadata extractMetadata(final #NotNull Page<U> page) {
return new PageMetadata(page.getSize(), page.getNumber(), page.getTotalElements(), page.getTotalPages());
}
}

Unexpected and unwanted div element in return from Spring RestController

I return an object instance of the following class from a Spring RestController method.
package x
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
#XmlRootElement(name = "invoices")
public class Invoices implements Serializable {
private Info info;
private Set<Customer> customers = new HashSet<>();
private List<Invoice> invoices = new ArrayList<>();
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
#XmlElement(name = "customer")
public Set<Customer> getCustomers() {
return customers;
}
public void setCustomers(Set<Customer> customers) {
this.customers = customers;
}
#XmlElement(name = "invoice")
public List<Invoice> getInvoices() {
return invoices;
}
public void setInvoices(List<Invoice> invoices) {
this.invoices = invoices;
}
}
The Controller method has the signature;
#RequestMapping(value = "/invoice", method = RequestMethod.GET, produces = "application/xml; charset=UTF-8")
This returns an XML with an unexpected div element and an attribute named slick_uniqueid on the top element. How do I get rid of this, and where does this come from?
<invoices slick-uniqueid="3">
<div>
<a id="slick_uniqueid" />
</div>
I found the answer to this myself. The raw response from the server does not include this attribute, nor the extra element. It's chrome that modifies the XML slightly when it displays it in-browser. The attribute and element is not there if I do a 'view source' either. Strange. I have never noticed that before

Problem about controller and dao functions

i made some small project
there are just add, delete, showlist functions
add and delete functions good work but get list functions are didn't work.
(in my project memoservice.getAll() function didn't work well)
so i try to get lists like this,
List <Memo> mem = getAll();
but there are no return values;
what's the problem in my project. help me plz!
some codes are here.
MemoController.java
package springbook.sug.web;
import javax.inject.Inject;
import javax.inject.Provider;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import springbook.sug.domain.Memo;
import springbook.sug.service.MemoService;
import springbook.sug.web.security.LoginInfo;
#Controller
#RequestMapping("/memo")
public class MemoController {
#Autowired
private MemoService memoService;
private #Inject Provider<LoginInfo> loginInfoProvider;
#RequestMapping("/list")
public String list(ModelMap model) {
model.addAttribute(this.memoService.getAll());
return "memo/list";
}
#RequestMapping("/list/{userId}")
public String list(#PathVariable int userId, ModelMap model) {
model.addAttribute(this.memoService.get(userId));
return "memo/list";
}
#RequestMapping("/delete/{memoId}")
public String delete(#PathVariable int memoId) {
this.memoService.delete(memoId);
return "memo/deleted";
}
#RequestMapping("/add/")
public String showform(ModelMap model) {
Memo memo = new Memo();
model.addAttribute(memo);
return "memo/add";
}
#RequestMapping(method=RequestMethod.POST)
public String add(#ModelAttribute #Valid Memo memo, BindingResult result, SessionStatus status) {
if (result.hasErrors()) {
return "list";
}
else {
this.memoService.add(memo);
status.setComplete();
return "redirect:list";
}
}
}
MemoService.java
package springbook.sug.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import springbook.sug.dao.MemoDao;
import springbook.sug.domain.Memo;
#Service
#Transactional
public class MemoServiceImpl implements MemoService{
private MemoDao memoDao;
#Autowired
public void setMemoDao(MemoDao memoDao) {
this.memoDao = memoDao;
}
public Memo add(Memo memo) {
memo.initDates();
return this.memoDao.add(memo);
}
public void delete(int memoId) {
this.memoDao.delete(memoId);
}
public Memo get(int userId) {
return this.memoDao.get(userId);
}
public Memo update(Memo memo) {
return this.memoDao.update(memo);
}
public List<Memo> getAll() {
return this.memoDao.getAll();
}
}
MemoDao.java
package springbook.sug.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;
import springbook.sug.domain.Memo;
#Repository
public class MemoDaoJdbc implements MemoDao {
private SimpleJdbcTemplate jdbcTemplate;
private SimpleJdbcInsert memoInsert;
private RowMapper<Memo> rowMapper =
new RowMapper<Memo>() {
public Memo mapRow(ResultSet rs, int rowNum) throws SQLException {
Memo memo = new Memo();
memo.setMemoId(rs.getInt("memoId"));
memo.setMemoContents(rs.getString("memoContents"));
memo.setMemoRegister(rs.getString("memoRegister"));
memo.setCreated(rs.getDate("created"));
return memo;
}
};
#Autowired
public void init(DataSource dataSource) {
this.jdbcTemplate = new SimpleJdbcTemplate(dataSource);
this.memoInsert = new SimpleJdbcInsert(dataSource)
.withTableName("memos")
.usingGeneratedKeyColumns("memoId");
}
public Memo add(Memo memo) {
int generatedId = this.memoInsert.executeAndReturnKey(
new BeanPropertySqlParameterSource(memo)).intValue();
memo.setMemoId(generatedId);
return memo;
}
public Memo update(Memo memo) {
int affected = jdbcTemplate.update(
"update memos set " +
"memoContents = :memoContents, " +
"memoRegister = :memoRegister, " +
"created = :created, " +
"where memoId = :memoId",
new BeanPropertySqlParameterSource(memo));
return memo;
}
public void delete(int memoId) {
this.jdbcTemplate.update("delete from memos where memoId = ?", memoId);
}
public int deleteAll() {
return this.jdbcTemplate.update("delete from memos");
}
public Memo get(int memoId) {
try {
return this.jdbcTemplate.queryForObject("select * from memos where memoId = ?",
this.rowMapper, memoId);
}
catch(EmptyResultDataAccessException e) {
return null;
}
}
public List<Memo> search(String memoRegister) {
return this.jdbcTemplate.query("select * from memos where memoRegister = ?",
this.rowMapper, "%" + memoRegister + "%");
}
public List<Memo> getAll() {
return this.jdbcTemplate.query("select * from memos order by memoId desc",
this.rowMapper);
}
public long count() {
return this.jdbcTemplate.queryForLong("select count(0) from memos");
}
}
Are you getting an exception when running the code? If so, stack trace is needed. If not, do you have data in your table to return? How are you injecting datasource into your dao implementation? Your application context might help.

Resources