repo.save not storing data in H2 - spring

`I have created simple spring project where I am using requestmapping to store data in my H2 database. I am getting parameters in URL but data is getting saved.
I am new in spring boot and facing this issue. Please help me with this. Thanks
//Controller Class
#Controller
public class TrialTwoController {
#Autowired
Repository repos;
#RequestMapping("/")
public String home() {
return "home.jsp";
}
#RequestMapping(path="/addUser")
public TrailTwo post(#RequestBody TrailTwo trail) {
repos.save(trail);
return trail;
}
}
//Model class
#Entity
public class TrailTwo {
#Id
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Repository Interface
public interface Repository extends JpaRepository<TrailTwo, Integer> {
}
application properties
spring.h2.console.enabled=true
spring.datasource.platform=h2
spring.datasource.url=jdbc:h2:mem:anshul
`

Inside your controller, you want to return TrailTwo entity. However, because you use #Controller and not #RestController, Spring won't be able to return the entity and will try to render the view instead which will result in the exception.
In order to fix this problem, you need to add #ResponseBody for in your method.
#RequestMapping(path="/addUser")
public #ResponseBody TrailTwo post(#RequestBody TrailTwo trail) {
repos.save(trail);
return trail;
}
You can also separate the concerns and have UserController which will be annotated with #RestController and ViewController which will be annotated with #Controller. This way, you won't have to add #ResponseBody annotation inside #RestController.
On another note, make sure to use POST http method for adding new entities. Instead of using #RequestMapping, you can use #PostMapping which will limit the supported http methods to POST. For POST, parameters need to be passed as a part of request body.
Make sure you understand http methods and how to use them to build robust REST apis. It will make your life easier. You can read about different http methods and how to use them here https://restfulapi.net/http-methods/
For the full working example, you can take a look here: https://github.com/CaptainAye/repository-h2-sample

Related

JSON field Desrializing to lowercase in Spring Boot

I have a Spring Boot Controller -
#RestController
public class UserController {
#PostMapping
#ResponseStatus(CREATED)
public UserResponse register( #Valid #RequestBody UserRequest userRequest) {
//return ....
}
}
Below is UserRequest.java
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
public class UserRequest {
private String email;
//other property
}
I am sending below json in request body -
{
"email" : "TEST#Example.com",
//some other fields.
}
Sometime client send email in uppercase or in camel case so in userRquest I want to change value of email field to lowercase like test#example.com while de serializing to UserRequest Object.
Is there any easy way to do this. Can I introduce my own annotation like #ToLowerCase how I can create my own annotation and use that at field level in UserRequest.
There is no easy way just by introducing a new annotation #ToLowerCase,
because then you would also need to implement some annotation processor
for doing the real conversion work.
But you can achieve your goal in a slightly different way.
In your UserRequest class annotate the email property
with #JsonDeserialize and specify a converter there.
#JsonDeserialize(converter = ToLowerCaseConverter.class)
private String email;
You need to implement the converter class by yourself,
but it is easy by extending it from StdConverter.
public class ToLowerCaseConverter extends StdConverter<String, String> {
#Override
public String convert(String value) {
return value.toLowerCase();
}
}
Jackson will use the setter methods in your class.
Perform the conversion to lower case in the setter.
For example
public void setEmail(String newValue)
{
email = StringUtils.lowerCase(newValue);
}
StringUtils is an apache commons class.
You can make a general StringDeserializer and register it in ObjectMapper as shown below:-
StringDeserializer class
public final class StringDeserializer extends StdDeserializer<String> {
public StringDeserializer() {
super((Class<String>) null);
}
#Override
public String deserialize(JsonParser parser, DeserializationContext context) throws IOException {
JsonToken token = parser.getCurrentToken();
if (token == JsonToken.VALUE_STRING) {
String text = parser.getText();
return text == null ? null : text.toLowerCase().trim();
}
return null;
}
}
JacksonConfiguration class
#Configuration
public class JacksonConfiguration {
#Autowired
void mapper(ObjectMapper mapper) {
mapper.registerModule(initModule());
}
private Module initModule() {
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new StringDeserializer());
return module;
}
}
The above code makes jackson deserialize all strings to lowercase and trimmed.

Get all documents from an index using spring-data-elasticsearch

I am trying to connect to my external ElasticSearch server with Spring Boot.
If I do a curl from command line, I get expected results.
curl "http://ipAddr:9200/indexName/TYPE/_search?pretty=true"
But getting this error when I try to access it via Spring Boot.
<html><body><h1>Whitelabel Error Page</h1><p>This application has no explicit mapping for /error, so you are seeing this as a fallback.</p><div id='created'>Mon Sep 11 12:39:15 IST 2017</div><div>There was an unexpected error (type=Internal Server Error, status=500).</div><div>Could not write JSON: (was java.lang.NullPointerException); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: java.util.ArrayList[0]->org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl["facets"])</div></body></html>
Not sure why a NullPointerException and what is aggregartion.impl
Here is my Spring Application:
Controller:
#RestController
public class PojoController {
#Autowired
PojoService pojoService;
#RequestMapping(value = "/", method=RequestMethod.GET)
public #ResponseBody String index() {
return new String("Welcome:)");
}
#RequestMapping(value = "/all", method = RequestMethod.GET,
produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseBody List<POJO> findAll() {
try {
List<POJO> pojoObj = pojoService.findAll();
return pojoObj;
} catch (Exception exp) {
exp.printStackTrace();
return null;
}
}
}
Repository:
#Repository
public interface PojoRepository extends ElasticsearchRepository<POJO, Integer> {
List<POJO> findAll();
}
Service:
#Service
public class POJOServiceImpl implements POJOService{
private POJORepository pojoRepository;
private ElasticsearchTemplate elasticsearchTemplate;
#Autowired
public void setPojoRepository(PojoRepository pojoRepository) {
this.pojoRepository = pojoRepository;
}
public POJO findOne(String id) {
return pojoRepository.findOne(id);
}
public List<POJO> findAll() {
return (List<POJO>) pojoRepository.findAll();
}
}
POJO class:
#Document(indexName = "INDEX", type = "TYPE")
public class POJO {
#Id
private Integer id;
private String name;
public POJO(){
// empty
}
public POJO(Integerid, String name) {
super();
this.id = id;
this.name = name;
}
// getters and setters
}
I should be able to query all the documents in the index. Later on, I will try and use filters etc.
Any help is appreciated. Thanks :)
It looks like Jackson has a problem with handling your POJO (probably related to this issue: DATAES-274) - the problematic part is casting in repository from Iterable collection to List.
Update
In case of repositories, spring-data-elasticsearch behaves a bit different than you would expect. Taking your example:
#Repository
public interface PojoRepository extends ElasticsearchRepository<POJO, Integer> {
List<POJO> findAll();
}
and after calling in your rest controller:
List<POJO> pojoObj = pojoService.findAll();
in debugger you will see something like this:
You would expect that pojoObj list contains objects of POJO class.
And here comes the surprise - pojoObj ArrayList contains one object of AggregatedPageImpl type and its content field is the right list that contains your POJO objects.
This is the reason why you get:
Could not write JSON: ... java.util.ArrayList[0]->org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl[\"facets\"])
As I wrote before, Jackson cannot handle this while serializing POJO objects.
Solution 1
Let repositories return Iterable collection (by default).
#Repository
public interface PojoRepository extends ElasticsearchRepository<POJO, Integer> {
}
Move the conversion part to the service but use some utility method (here with Guava) in order to have it like this:
import com.google.common.collect.Lists;
public List<POJO> findAll() {
return Lists.newArrayList(pojoRepository.findAll());
}
Solution 2
Use Page in repository (here simplified version without parameters):
#Repository
public interface PojoRepository extends ElasticsearchRepository<POJO, Integer> {
Page<TestDto> findAll();
}
If you still want to operate on list - get content from page in service:
public List<POJO> findAll() {
return testDtoRepository.findAll().getContent();
}

Spring Boot validation with Hibernate Validator

Anyone know if it`s possible to create one method in my entity, to execute when I put the annotation #Valid in my class?
Example:
I have this Object:
public class Area {
#NotEmpty
private String unidade;
#NotNull
private double tamanho;
public String getUnidade() {
return unidade;
}
public void setUnidade(String unidade) {
this.unidade = unidade;
}
public double getTamanho() {
return tamanho;
}
public void setTamanho(double tamanho) {
this.tamanho = tamanho;
}
}
And I have this method:
#RestController
#RequestMapping("/recolhimento")
public class RecolhimentoController {
#RequestMapping(method = RequestMethod.GET)
public boolean getRecolhimento(#Valid Area area){
...
}
}
so when I call this method the Spring Boot will validate my model Area( but I want to create one method that will be execute when I use #Valid.
it`s possible? how?
Yes, it is possible.
You can find examples in this project: https://github.com/malkusch/validation

Implementing/Overriding MongoRepository Keep HATEOAS Formatting

I have a simple MongoRepository I would like to modify to return the generated ObjectId on post(save()).
public interface EmployeeRepository extends MongoRepository<Employee, String>
{
public void delete(Employee employee);
public Employee save(Employee employee);
public Employee findOne(String id);
public List<Employee> findAll();
public Employee findByName(String principal);
}
I have explored ways to generate the id client side and pass it in the post BUT I really want Spring to handle this.
I've tried intercepting with a controller and returning the object in the ResponseBody, like so:
#RequestMapping(value=URI_EMPLOYEES, method=RequestMethod.POST)
public #ResponseBody Employee addEmployee(#RequestBody Employee employee) {
return repo.save(employee);
}
Problem with this is it forces me to re-work all the HATEOAS related logic Spring handles for me. Which is a MAJOR pain. (Unless I'm missing something.)
What's the most effective way of doing this without having to replace all of the methods?
Was using #Controller instead of #RepositoryRestController which was causing things to act up.
We can now easily override the POST method on this resource to return whatever we want while keeping spring-data-rest's implementation of the EmployeeRepository intact.
#RepositoryRestController
public class EmployeeController {
private final static String URI_EMPLOYEES = "/employees";
#Autowired private EmployeeRepository repo;
#RequestMapping(value=URI_EMPLOYEES, method=RequestMethod.POST)
public #ResponseBody HttpEntity<Employee> addVideo(#RequestBody Employee employee) {
return new ResponseEntity<Employee>(repo.save(employee), HttpStatus.OK);
}
}
Have a look at the interface:
public Employee save(Employee employee)
You can get the saved entity by simply doing
Employee saved = repository.save(employee);
return saved.getId();
The being said, you surely can generate the Id and set it via setId(). But once an ID is saved, it is immutable. Changing the Id and saving that entity would result in a new document saved in MongoDB.

#PathVariable not binding with #RequestBody

When I don't use #RequestBody the #PathVariable id is automatically set at my Entity class. But if I use #RequestBody it's not. I need that the id of Entity is set before my GenericValidator executes validation. Why does it work without #RequestBody and not with it?
The Entity class:
public class Entity {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
//...
}
The controller class:
#Controller
#RequestMapping(value = "/entity")
public class EntityController {
#Autowired
private GenericValidator validator;
#InitBinder
private void initBinder(WebDataBinder binder) {
binder.addValidators(validator);
}
#RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public #ResponseBody Response update(
#PathVariable String id,
#Valid #RequestBody Entity entity)
{
//...
}
}
When used alone, #Valid works much like #ModelAttribute. The Entity method argument would be retrieved from the Model or instantiated, the WebDataBinder would handle the data binding process (this is when the id would be set), and then validation would occur.
#RequestBody arguments do not go through the data binding process like #ModelAttribute arguments. They're created via an HttpMessageConverter using the body of the request instead of matching the names of request parameters and path variables to the names of your object's fields. When combined with #Valid, the configured validator is run against the new object but #ModelAttribute style data binding still does not occur.

Resources