Getting empty answer Mongodb - spring

Hi there im having some issues with MongoDb i have a CRUD and this is the code im using
First the POJO:
#Data
#Document(collection = "Informacion")
public class Informacion {
//Declaration code
public Informacion(Pais pais, Date fechaCreacion, String nombre, Boolean sexo,
Date fechaNacimiento, List<Preferencias> preferencias, String numTelefono, String usuario,
List<RedesSociales> redes, String contraseniaTW, String contraseniaFB, String contraseniaIG,
Grupo grupo, String paqChip, String email, String contraseniaMail, String fuente,
Date fechaRecarga) {
this.pais = pais;
this.fechaCreacion = fechaCreacion;
this.nombre = nombre;
this.sexo = sexo;
this.fechaNacimiento = fechaNacimiento;
this.preferencias = preferencias;
this.numTelefono = numTelefono;
this.usuario = usuario;
this.redes = redes;
this.contraseniaTW = contraseniaTW;
this.contraseniaFB = contraseniaFB;
this.contraseniaIG = contraseniaIG;
this.grupo = grupo;
this.paqChip = paqChip;
this.email = email;
this.contraseniaMail = contraseniaMail;
this.fuente = fuente;
this.fechaRecarga = fechaRecarga;
}
}
Now the DAO:
#Repository
public interface informacionRepo extends MongoRepository<Informacion,String> {
Informacion findByIdInformacion(String id);
}
And the controller:
#RestController
#RequestMapping("/Informacion")
public class InformacionControlador {
#Autowired
private informacionRepo informacioRepo;
public InformacionControlador(informacionRepo informacioRepo) {
this.informacioRepo = informacioRepo;
}
#GetMapping("/Listar")
public List<Informacion> getAll(){
List<Informacion> info = this.informacioRepo.findAll();
System.out.println(info.isEmpty());
return info;
}
#PutMapping
public void insert(#RequestBody Informacion informacion){
this.informacioRepo.insert(informacion);
}
public void update(#RequestBody Informacion informacion){
this.informacioRepo.save(informacion);
}
#DeleteMapping("/Listar/{id}")
public void delete(#PathVariable("id") String id){
this.informacioRepo.deleteById(id);
}
#GetMapping("/Listar/{id}")
public Informacion getById(#PathVariable("id") String id){
Informacion info = this.informacioRepo.findByIdInformacion(id);
return info;
}
}
Im using POSTMAN to test the methods above but im getting empty answers, the data is already set on the Database, im using a method call seeder that fills the data also y check it with robo mongo and the data is there but still getting empty answers also when i try the insert method i get 403 error.
Thanks for your help
This is the answer seen from the web browser

The problem was that im using the annotation #Data from lombok but i didnt enable annotation processing in the IDE just enable it and works :D

Related

Problem when attempting a saveAndFlush commit (JPA ) when primary key is auto-generated from postGres trigger

I am using spring JPA to attempt to write records to a postGres DB. At the time of the commit, I am getting the following error:
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "col_id" violates not-null constraint
Detail: Failing row contains (null, null, null, null, null)
I have the following repository interface:
public interface MyRepo extends JpaRepository <MyModel, String> {
}
, the following model class:
#Entity
#Validated
#Table(name = "my_table", schema="common")
public class MyModel {
#Id
#Column(name = "col_id")
private String id;
#Column(name = "second_col")
private String secCol;
#Column(name = "third_col")
private String thirdCol;
#Column(name = "fourth_col")
private String fourthCol;
#Column(name = "fifth_col")
private String fifthCol;
public MyModel() {
}
public MyModel(String id, String secCol, String thirdCol, String fourthCol, String fifthCol) {
this.id = id;
this.secCol = secCol;
this.thirdCol = thirdCol;
this.fourthCol = fourthCol;
this.fifthCol = fifthCol;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSecCol() {
return secCol;
}
public void setSecCol(String secCol) {
this.secCol = secCol;
}
public String getThirdCol() {
return thirdCol;
}
public void setThirdCol(String thirdCol) {
this.thirdCol = thirdCol;
}
public String getFourthCol() {
return fourthCol;
}
public void setFourthCol(String fourthCol) {
this.fourthCol = fourthCol;
}
public String getFifthCol() {
return fifthCol;
}
public void setFifthCol(String fifthCol) {
this.fifthCol = fifthCol;
}
}
, and the relevant part of the service class:
public MyModel myModel (MyModel myModel) {
MyModel mm = null;
try {
mm = myRepo.saveAndFlush(myModel);
} catch ( Exception e) {
e.printStackTrace();
}
return mm;
}
UPDATE:
I finally realized that my problem is due to a database trigger that auto-generates primary key against a complex business rule. Also, I assume I might need to use a custom save method rather than the default repo.saveAndFlush? I would be grateful for any ideas given new information. Thanks!
I reproduced the exact same code in a test project with Postgres and it worked well for me. You are absolutely correct that the values of the model class are not populated. You must share your controller also. It may really help me to help you if I can get a look where your service is being called from. Only that will help me to deduce why your model values are being passed as null in the service call.

How to reference a properties value inside the schema attribute of an entity?

There is an entity :
#Entity
#Table(name = "ITMMASTER" , schema = "TOMCTB")
public class Article {
#Id
#Column(name = "ITMREF_0")
private String code_article;
#Column(name = "ACCCOD_0")
private String acccod;
public String getCode_article() {
return code_article;
}
public void setCode_article(String code) {
this.code_article = code;
}
public String getAcccod() {
return acccod;
}
public void setAcccod(String acccod) {
this.acccod = acccod;
}
}
I want to make the schema attribute to be dynamic depending on a properties file property value , for example : env.schema = TOMEXPL.
How to achieve that ?
I didn't tried it but I guess this should work.
public class DynamicNamingStrategy extends DefaultNamingStrategy {
#Value("db.table.name")
private String name;
#Override
public String tableName(String tableName) {
return name;
}
...
}
SessionFactory sessionFactory;
Configuration config = new AnnotationConfiguration()
.configure("hibernate.cfg.xml")
.setNamingStrategy( new DynamicNamingStrategy() );
sessionFactory = config.buildSessionFactory();
session = sessionFactory.openSession();

org.springframework.web.bind.MissingServletRequestParameterException: Required int parameter

Hi i am new for WebServices and In my My-Sql Database I have student table with some columns those are "user_id", and "name" and "marks"
I want to update one row based on userId for this i wrote below code but i am getting exception like below can some one help me please
Controller [com.ensis.sample.controller.SampleController]
Method [public com.ensis.sample.model.StatusObject com.ensis.sample.controller.SampleController.updateStudentListById(int)]
org.springframework.web.bind.MissingServletRequestParameterException: Required int parameter 'userId' is not present
controller:-
#RequestMapping(value="/update",method=RequestMethod.POST,produces={"application/json"})
#ResponseBody
public StatusObject updateStudentListById(#RequestParam int userId){
return userService.updateStudentDetailsById(userId);
}
UserService:-
#Transactional
public StatusObject updateStudentDetailsById(int id){
Users users = usersdao.updateStudentDetailsById(id);
if(users!=null){
users.setName("Sample");
users.setMarks(99.99);
}
StatusObject statusObject = new StatusObject();
boolean status = usersdao.updateUser(users);
if(status==true){
statusObject.setStatus(false);
statusObject.setMessage("Success");
return statusObject;
}else{
statusObject.setStatus(true);
statusObject.setMessage("Failure");
return statusObject;
}
}
UserDao:-
public Users updateStudentDetailsById(int userId){
System.out.println("UserId is=====>"+userId);
String hql = "FROM Users s WHERE " + "s.user_id = :userId";
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery(hql);
query.setParameter("user_id", userId);
List<?>list = query.list();
Iterator<?>itr = list.iterator();
if(itr.hasNext()){
Users users = (Users)itr.next();
return users;
}
session.flush();
session.clear();
return null;
}
Users:-
#Entity
#Table(name = "student")
public class Users {
#Id
private int user_id;
private String name;
private int rank;
private double marks;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public double getMarks() {
return marks;
}
public void setMarks(double marks) {
this.marks = marks;
}
#Krish, when you are posting something, you usually use Spring's #RequestBodyas seen below:
#RequestMapping(value="/update",method=RequestMethod.POST,produces={"application/json"})
#ResponseBody
public StatusObject updateStudentListById(#RequestBody User user){
return userService.updateStudentDetailsById(userId);
}
You need to pass the JSON object to this controller method. Spring will deserialize the JSON for you.
When you say #RequestParam, it expects to find the request parameters like
/update?userId=1
PS: It is not good practice to send just the ID to update a resource.
Are you using it as a RestController.The excecption is coming from the controller as it expects a parameter from the client.Please verify if you are passing the userID in the pathParam.

JAXB Error while using in SpringREST to return a ArrayList of a domain object

I am trying to use JAXB in Spring RESTful webservice.
My code is as follows:
#RequestMapping(value = "/countries",
method = RequestMethod.GET,
headers="Accept=application/xml, application/json")
public #ResponseBody CountryList getCountry() {
logger.debug("Provider has received request to get all persons");
// Call service here
CountryList result = new CountryList();
result.setData(countryService.getAll());
return result;
}
The CountryList.java class looks like:
#XmlRootElement(name="countries")
public class CountryList {
#XmlElement(required = true)
public List<Country> data;
#XmlElement(required = false)
public List<Country> getData() {
return data;
}
public void setData(List<Country> data) {
this.data = data;
}
}
The Country.java looks like:
#XmlRootElement(name="country")
public class Country {
private Calendar createdDt;
private String updatedBy;
private String createdBy;
private Long id;
private String countryName;
private Calendar updatedDt;
// getters and setters for all attributes goes here
}
Now, when I access the method getCountry(), I am getting the following exception
Caused by: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions
Class has two properties of the same name "data"
this problem is related to the following location:
at public java.util.List com.cisco.bic.services.model.CountryList.getData()
at com.cisco.bic.services.model.CountryList
this problem is related to the following location:
at public java.util.List com.cisco.bic.services.model.CountryList.data
at com.cisco.bic.services.model.CountryList
Would anyone has any idea why is this error coming. Am I doing anything wrong in the annotaion part ??
Please help.
Regards
Saroj
You can't annotate both the getter/setter and the field, you need to decide on one of them.

Problems with WebDataBinder and Set.Class

i am having trouble with binding my data from a form :
I have two class
#Entity
#Table(name = "ROLES")
public class Role implements GenericDomain {
private Long id;
private String code;
private String name;
private Set<Privilege> privileges = new HashSet<Privilege>(0);
public Role() {}
/* getter and setter*/
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name = "ROLES_PRIVILEGES"
, joinColumns = { #JoinColumn(name = "ROLE_ID") }
, inverseJoinColumns = { #JoinColumn(name = "PRIVILEGE_ID") }
)
public Set<Privilege> getPrivileges() {
return this.privileges;
}
public void setPrivileges(Set<Privilege> privileges) {
this.privileges = privileges;
}
/* overide of hascode, equals*/
}
And
#Entity
#Table(name = "PRIVILEGES")
public class Privilege implements GenericDomain {
private Long id;
private String code;
private Set<Role> roles = new HashSet<Role>(0);
public Privilege() {}
/* getter and setter*/
#ManyToMany(cascade=CascadeType.REFRESH, mappedBy="privileges")
public Set<Role> getRoles() {
return this.roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
#Override
public String toString(){
return this.getCode() + this.getComment();
}
/*overide equals and hascode*/
and in my controller i have :
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Set.class, "privileges", new CustomCollectionEditor(Set.class) {
#Override
protected Object convertElement(Object element) {
return (element == null)?null:privilegeService.getOne(Integer.parseInt((String)element));
}
});
}
#RequestMapping(value = "edit", method = RequestMethod.POST)
public String saveOldRole( #ModelAttribute("role") Role role
, BindingResult result
, ModelMap model
) {
validator.validate(role, result);
if (result.hasErrors()){
logger.error(result.getAllErrors());
model.addAllAttributes(result.getModel());
return "/admin/role/edit";
}
logger.info(role.getPrivileges());
Iterator p = role.getPrivileges().iterator();
while(p.hasNext()){
logger.info(p.next().getClass());
}
roleService.saveOrUpdate(role);
model.addAttribute("roles", roleService.getAll());
sessionStatus.setComplete();
return "redirect:/admin/role/list.do";
}
and my debug is
role.RoleController:93 - [[MANAGE_USERS], [MANAGE_ROLES]]
role.RoleController:96 - class java.util.LinkedHashSet
role.RoleController:96 - class java.util.LinkedHashSet
22:29:44,915 ERROR tomcat-http--7 property.BasicPropertyAccessor:194 - IllegalArgumentException in class: com.stunaz.domain.Privilege, getter method of property: id
I dont understand why at 96, the class type is java.util.LinkedHashSet, i thought it should be Privileges.
I dont understand why my role.getPrivileges() is a Set of Set, it should be a Set of Privilege.
Of course at saveOrUpdate am getting an error.
finaly!!!
there were no bug at all!
i updated my spring jar from 3.0.5.RELEASE to 3.1.0.M1, and voila : somthing stopped working with webdatabinder and CustomCollectionEditor.
i just rollback to 3.0.5.RELEASE and everything is fine.

Resources