I try to test my JPA in Springboot but I get error as following. Referred several threads related to it and tried every solution but none of them are working.
If I use #MockBean for repository class, the data is not persisting and retrieving. IF I use #Autowired, I am getting the above error.
I used #SpringbootTest as well as #DataJpaTest with #ContextConfiguration but none of the annotations solves the problem. What am I missing here? Please help.
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [de.api.repository.StyledLayerDescriptorStorageRepository]: Specified class is an interface
import de.api.entity.StyledLayerDescriptorEntity;
import de.api.entity.StyledLayerDescriptorEntityBuilder;
import de.api.repository.StyledLayerDescriptorStorageRepository;
import de.api.service.StyledLayerDescriptorStorageService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.context.annotation.Profile;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit4.SpringRunner;
import java.time.OffsetDateTime;
import java.util.Optional;
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = {de.api.repository.StyledLayerDescriptorStorageRepository.class})
#DataJpaTest
#EnableAutoConfiguration
public class StyledLayerDescriptorStorageRepositoryTest {
#Autowired
StyledLayerDescriptorStorageRepository styledLayerDescriptorStorageRepository;
#Test
#Profile(("Test"))
public void testRepository(){
String sldId = "5c0405b0-2a09-4d52-a702-6395445bd575";
StyledLayerDescriptorEntity sld =
new StyledLayerDescriptorEntityBuilder(
sldId,
OffsetDateTime.parse("2021-03-11T09:00:07Z"),
"my content")
.build();
styledLayerDescriptorStorageRepository.save(sld);
Optional<StyledLayerDescriptorEntity> sldRes = styledLayerDescriptorStorageRepository.findById(sldId);
}
}
Repository class
package de.api.repository;
import de.api.entity.StyledLayerDescriptorEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
import java.time.OffsetDateTime;
import java.util.List;
#Component
#Repository
public interface StyledLayerDescriptorStorageRepository extends JpaRepository<StyledLayerDescriptorEntity, String> {
public final static String FIND_BY_TIME_STAMP = "SELECT S.id FROM StyledLayerDescriptorEntity S WHERE S.timestamp<:timestamp";
#Query(FIND_BY_TIME_STAMP)
public List<String> findByTimeStamp(#Param("timestamp")OffsetDateTime timestamp);
}
Entity class
package de.api.entity;
import javax.persistence.*;
import java.time.OffsetDateTime;
#Entity
#Table(name = "StyledLayerDescriptor")
public class StyledLayerDescriptorEntity {
#Id private String id;
private OffsetDateTime timestamp;
#Column(columnDefinition = "NVARCHAR(max)")
private String sldContent;
public StyledLayerDescriptorEntity() {}
public StyledLayerDescriptorEntity(String id, OffsetDateTime timestamp, String sldContent) {
this.id = id;
this.timestamp = timestamp;
this.sldContent = sldContent;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSldContent() {
return sldContent;
}
public void setSldContent(String sldContent) {
this.sldContent = sldContent;
}
public OffsetDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(OffsetDateTime timestamp) {
this.timestamp = timestamp;
}
}
Entity Builder
package de.api.entity;
import java.time.OffsetDateTime;
public class StyledLayerDescriptorEntityBuilder {
private String id;
private OffsetDateTime timestamp;
private String sldContent;
public StyledLayerDescriptorEntityBuilder(String id, OffsetDateTime timestamp, String sldContent) {
this.id = id;
this.timestamp = timestamp;
this.sldContent = sldContent;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public OffsetDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(OffsetDateTime timestamp) {
this.timestamp = timestamp;
}
public String getSldContent() {
return sldContent;
}
public void setSldContent(String sldContent) {
this.sldContent = sldContent;
}
public StyledLayerDescriptorEntity build() {
return new StyledLayerDescriptorEntity(id, timestamp, sldContent);
}
}
Related
Hello guys I need help to create a query to use in my #Repository.
This is the sql query consult
select * from sig_versions where sft_product_name like 'kiadoc-desktop' order by created_date DESC limit 1;
And this is the output
I don't know how to create the hibernate query using Hibernate and criteria
Now how can I call this from my #Repository
public String getSoftwareVersion(String name) throws InternalErrorException {
logger.info("getSoftwareVersion " + name);
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(this.typeParameterClass);
criteria.add(Restrictions.eq("sft_product_name", name));
return ((SoftwareVersion) criteria.uniqueResult()).get_Version();
}
I'm getting the InvocationTargetException
These are my files
package ar.com.lakaut.sig.core.dao;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
import com.curcico.jproject.core.exception.InternalErrorException;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import java.util.List;
import com.curcico.jproject.core.daos.BaseAuditedEntityDaoImpl;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
#Repository
public class SoftwareVersionDaoImpl extends BaseAuditedEntityDaoImpl<SoftwareVersion> implements SoftwareVersionDao {
public SoftwareVersionDaoImpl() { super(); }
Logger logger = Logger.getLogger(getClass());
public String getSoftwareVersion(String name) throws InternalErrorException {
logger.info("getSoftwareVersion " + name);
Criteria criteria = this.sessionFactory.getCurrentSession().createCriteria(this.typeParameterClass);
criteria.add(Restrictions.eq("sft_product_name", name));
return ((SoftwareVersion) criteria.uniqueResult()).get_Version();
}}
And the entity
package ar.com.lakaut.sig.core.domain;
import com.curcico.jproject.core.entities.BaseAuditedEntity;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "sig_versions")
#SQLDelete(sql="UPDATE sig_versions SET deleted = '1' WHERE version_id = ? and version = ?")
#Where(clause="deleted is null")
public class SoftwareVersion extends BaseAuditedEntity implements Serializable {
public SoftwareVersion() {}
private String product_name;
private String sft_version;
private String obs;
#Id
#SequenceGenerator(name = "id_generator", sequenceName = "sig_versions_config_seq", allocationSize = 1)
#GeneratedValue(generator = "id_generator", strategy =GenerationType.SEQUENCE)
#Column(name = "sft_id", unique = true, nullable = false)
public Integer getId() { return this.id; }
#Column(name = "sft_product_name", nullable = false)
public String getProductName() { return product_name; }
public void setProductName(String product_name) { this.product_name = product_name; }
#Column(name = "sft_version", nullable = false)
public String get_Version() { return sft_version; }
public void set_Version(String version) { this.sft_version = version; }
#Column(name = "sft_obs", nullable = false)
public String getObs() { return obs; }
public void setObs(String obs) { this.obs = obs; }
}
The #Service
package ar.com.lakaut.sig.core.service;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
import com.curcico.jproject.core.exception.BaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.curcico.jproject.core.services.BaseAuditedEntityServiceImpl;
import ar.com.lakaut.sig.core.dao.SoftwareVersionDao;
import org.apache.log4j.Logger;
#Service("SoftwareVersionService")
public class SoftwareVersionServiceImpl extends BaseAuditedEntityServiceImpl<SoftwareVersion, SoftwareVersionDao> implements SoftwareVersionService {
Logger logger = Logger.getLogger(SoftwareVersionServiceImpl.class);
#Override
public String getSoftwareVersion(String name) throws BaseException {
logger.info("softwareVersionId: " + name);
return dao.getSoftwareVersion(name);
}
}
The Service
package ar.com.lakaut.sig.core.service;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
import com.curcico.jproject.core.services.BaseAuditedEntityService;
import com.curcico.jproject.core.exception.BaseException;
public interface SoftwareVersionService extends BaseAuditedEntityService<SoftwareVersion> {
/**
* Params: name
* Return
* Throws BaseException
*/
public String getSoftwareVersion(String name) throws BaseException;
}
The DAO
package ar.com.lakaut.sig.core.dao;
import com.curcico.jproject.core.daos.BaseAuditedEntityDao;
import com.curcico.jproject.core.exception.BaseException;
import com.curcico.jproject.core.exception.InternalErrorException;
import ar.com.lakaut.sig.core.domain.SoftwareVersion;
public interface SoftwareVersionDao extends BaseAuditedEntityDao<SoftwareVersion>{
String getSoftwareVersion(String name) throws InternalErrorException;
}
I know that this question is a duplicate, but I have tried many of the suggestions that I found with no effect.
I am a beginner to spring boot, and I am following a tutorial using Spring boot and Cassandra. I get this error once SpringApplication.run(ReadstrackerDataLoaderApplication.class, args) is executed.
ReadstrackerDataLoaderApplication.java
package com.readstracker.demo;
#SpringBootApplication(scanBasePackages = {"com.readstracker.repositories", "com.readstracker.entities"})
//#ComponentScan("repositories.AuthorRepository")
#EnableConfigurationProperties(DataStaxAstraProperties.class)
#EnableCassandraRepositories("com.readstracker.repositories")
#ComponentScan("com.readstracker.entities")
#Service
public class ReadstrackerDataLoaderApplication {
#Autowired
private AuthorRepository authorRepository;
public static void main(String[] args) {
SpringApplication.run(ReadstrackerDataLoaderApplication.class, args);
}
#PostConstruct
public void start() {
Author author = new Author();
author.setId("id");
author.setName("name");
author.setPersonalName("personalName");
authorRepository.save(author);
}
#Bean
public CqlSessionBuilderCustomizer sessionBuilderCustomizer(DataStaxAstraProperties astraProperties) {
Path bundle = astraProperties.getSecureConnectBundle().toPath();
return builder -> builder.withCloudSecureConnectBundle(bundle);
}
}
AuthorRepository.java
package com.readstracker.repositories;
import org.springframework.data.cassandra.repository.CassandraRepository;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import com.readstracker.entities.Author;
#Repository
public interface AuthorRepository extends CassandraRepository<Author, String> {
}
Author.java
package com.readstracker.entities;
import org.springframework.data.annotation.Id;
import org.springframework.data.cassandra.core.cql.PrimaryKeyType;
import org.springframework.data.cassandra.core.mapping.CassandraType;
import org.springframework.data.cassandra.core.mapping.CassandraType.Name;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.data.cassandra.core.mapping.Column;
import org.springframework.data.cassandra.core.mapping.PrimaryKeyColumn;
import org.springframework.data.cassandra.core.mapping.Table;
#Table(value = "author_by_id")
#Component
public class Author {
#Id
#PrimaryKeyColumn(name = "author_id", ordinal = 0, type = PrimaryKeyType.PARTITIONED)
private String id;
#Column("author_name")
#CassandraType(type = Name.TEXT)
private String name;
#Column("personal_name")
#CassandraType(type = Name.TEXT)
private String personalName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPersonalName() {
return personalName;
}
public void setPersonalName(String personalName) {
this.personalName = personalName;
}
}
Here is my project directory
I'm trying to do a simple CRUD in postgres with spring, but for no reason my IoD mechanism doesn't work and throws an error like this:
Description:
Parameter 0 of constructor in br.com.maptriz.formulario_dinamico.service.FormularioDinamicoService required a bean of type 'br.com.maptriz.formulario_dinamico.repository.FormularioDinamicoRepository' that could not be found.
Action:
Consider defining a bean of type 'br.com.maptriz.formulario_dinamico.repository.FormularioDinamicoRepository' in your configuration.
Here's my code:
FormularioDinamicoApplication.java
package br.com.maptriz.formulario_dinamico;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
// #EnableJpaRepositories("br.com.maptriz.formulario_dinamico.repository")
// #EnableScheduling
// #EnableDiscoveryClient
// #ComponentScan
#SpringBootApplication
public class FormularioDinamicoApplication {
public static void main(String[] args) {
SpringApplication.run(FormularioDinamicoApplication.class, args);
}
}
FormularioDinamico
package br.com.maptriz.formulario_dinamico.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "formulario_dinamico")
public class FormularioDinamico {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne
#JoinColumn(name="tipo_tabela")
private Long tabelaId;
private String name;
private String campos;
protected FormularioDinamico() {}
public FormularioDinamico(Long tabelaId, String name, String campos) {
this.tabelaId = tabelaId;
this.name = name;
this.campos = campos;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTabelaId() {
return this.tabelaId;
}
public void setTabelaId(Long tabelaId) {
this.tabelaId = tabelaId;
}
public String getName() {
return this.name;
}
public void setObservacao(String name) {
this.name = name;
}
public String getCampos() {
return this.campos;
}
public void setCampos(String campos) {
this.campos = campos;
}
#Override
public String toString() {
return "EntidadeGenerica{" +
"id=" + id +
", dataAtualizacao=" + tabelaId +
", dataCadastro=" + name +
", observacao='" + campos + '}';
}
}
FormlarioDinamicoController.java
package br.com.maptriz.formulario_dinamico.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.maptriz.formulario_dinamico.model.FormularioDinamico;
import br.com.maptriz.formulario_dinamico.service.FormularioDinamicoService;
#RestController
#RequestMapping
public class FormularioDinamicoController {
private final FormularioDinamicoService service;
#Autowired
public FormularioDinamicoController(FormularioDinamicoService service) {
this.service = service;
}
// #GetMapping
// public List<DynamicForm> getDynamicForm() {
// return dynamicFormService.getDynamicForm();
// }
#PostMapping("/create")
public void registrarNovoFormularioDinamico(#RequestBody FormularioDinamico formularioDinamico) {
System.out.println("TEST");
service.adicionarNovoFormularioDinamico(formularioDinamico);
}
}
FormularioDinamicoService.java
package br.com.maptriz.formulario_dinamico.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.maptriz.formulario_dinamico.model.FormularioDinamico;
import br.com.maptriz.formulario_dinamico.repository.FormularioDinamicoRepository;
#Service
public class FormularioDinamicoService {
private final FormularioDinamicoRepository repository;
#Autowired
public FormularioDinamicoService(FormularioDinamicoRepository repository) {
this.repository = repository;
}
// public List<DynamicForm> getDynamicForm() {
// return dynamicFormRepository.findAll();
// }
public void adicionarNovoFormularioDinamico(FormularioDinamico formularioDinamico) {
List<FormularioDinamico> topicos = repository.findAll();
System.out.println("HEREEEE");
System.out.println(topicos);
}
}
And finally FormularioDinamicoRepository.java
package br.com.maptriz.formulario_dinamico.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import br.com.maptriz.formulario_dinamico.model.FormularioDinamico;
public interface FormularioDinamicoRepository
extends JpaRepository<FormularioDinamico, Long> {
List<FormularioDinamico> findAll();
}
My Folder Structure:
src
main
java/br/com/maptriz/formulario_dinamico
controller
model
repository
service
FormularioDinamicoApplication.java
Add #Repository annotation on the interface FormularioDinamicoRepository. It should be working seamlessly.
The moment you add it spring identifies it as a bean and creates an object and injects the bean wherever autowired.
I went to develop an application to manage students in a university, I am looking for how to find students in relation to a date entered for that I have developed the following code lines:
1- Model student.java
package com.avatar.model;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.JoinColumn;
#Entity
#Table(name = "Students")
public class Student{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String nom;
private String prenom;
private String numTel;
private String mail;
#Temporal(TemporalType.DATE)
private Date dateCurrent;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "student_techno",
joinColumns = { #JoinColumn(name = "student_id") },
inverseJoinColumns = { #JoinColumn(name = "techno_id") })
private Set<Techno> techno = new HashSet<>();
public Student() {
}
#SuppressWarnings("unchecked")
public Student(String nom, String prenom,String numTel, String mail, Date dateCurrent,
) {
super();
this.nom = nom;
this.prenom = prenom;
this.numTel = numTel;
this.mail = mail;
this.dateCurrent = dateCurrent;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getNumTel() {
return numTel;
}
public void setNumTel(String numTel) {
this.numTel = numTel;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getdateCurrent() {
return dateCurrent;
}
public void setdateCurrent(Date dateCurrent) {
this.dateCurrent = dateCurrent;
}
#Override
public String toString() {
return "Student[nom=" + nom + ", prenom=" + prenom + ", numTel=" + numTel + ", mail="
+ mail + ", dateCurrent=" + dateCurrent+ "]";
}
}
2- Controller
package com.avatar.web;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.avatar.dao.StudentDao;
import com.avatar.model.Student;
#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("/avatar")
public class StudentController {
#Autowired
StudentDao studentdao;
#GetMapping(value = "/all-students")
public List<Student> listeDesStudent() {
List<Student> students= studentdao.findAll();
if (students.isEmpty())
throw new ProductNotFoundException("No student is registered in the database");
return students;
}
#GetMapping(value = "/all-students/dateCurrent/{dateCurrent}")
public List<Student> viewStudent(#PathVariable("dateCurrent") #DateTimeFormat(pattern = "yyyy-MM-dd") Date dateCurrent) {
Calendar c = Calendar.getInstance();
c.setTime(dateCurrent);
c.add(Calendar.DATE, 1);
dateCurrent = c.getTime();
return studentdao.findByDate(dateCurrent);
}
#GetMapping(value = "/all-students /techno/{nomTechno}")
List<Student > viewStudent(#PathVariable("nomTechno") String nomTechno) {
return studentdao.findDistinctByTechnoNomTechno(nomTechno);
}
#PostMapping(value = "/add-student")
public Student addStudent(#RequestBody Student student) {
Student studentAdded= studentdao.save(Student);
return studentAdded;
}
}
3- DAO
package com.avatar.dao;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.avatar.model.Student;
#Repository
public interface StudentDao extends JpaRepository<Student, String> {
List<Student> findByDate(Date dateCurrent);
List<> findDistinctByTechnoNomTechno(String nomTechno);
}
4- applications.properties
server.port= 8080
# MySQL Properties
spring.jpa.show-sql = true
spring.datasource.url= jdbc:mysql://localhost:3306/avatar?serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username=*****
spring.datasource.password=*****
# Hibernate Properties
spring.jpa.hibernate.ddl-auto=update
in my console i have:
Failed to create query for method public abstract java.util.List com.avatar.dao.StudentDao.findByDate(java.util.Date)! No property date found for type Student!
Please update DAO as per for below mentioned changes
If the field name is dateCurrent then findByDateCurrent.
package com.avatar.dao;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.avatar.model.Student;
#Repository
public interface StudentDao extends JpaRepository<Student, String> {
List<Student> findByDateCurrent(Date dateCurrent);
List<> findDistinctByTechnoNomTechno(String nomTechno);
}
You are missing field name, in Entity class it is not the date by dateCurrent, thus your JPA should be findByDateCurrent
I'm building a rest controller using Spring to handle request and Jackson to serialize data.However I followed tutorial online but I end up getting an error.
HTTP Status 406 -
type Status report
message
description The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
After Google for a while, I realized that it is because I don't have "application/json" as my "Accept" header in my request:
So I use a tool called Postman to manually add this "Accept" header in the request, send the request again, but still getting the same error:
I'm so confused, I've already included "application/json" as one of accepted data-type, why I still have this data-unsupported error? FYI, here is my Rest Controller class:
package mywebapp.controller;
import java.io.IOException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import mywebapp.dao.model.interfaces.PetDao;
import mywebapp.model.Pet;
#RestController
#RequestMapping(value = "petJson.htm")
public class PetControllerAjax {
private static final Logger LOG = LoggerFactory.getLogger(PetController.class);
public static Logger getLog() {
return LOG;
}
#Autowired
#Qualifier("PetDaoJpaImpl")
private PetDao petDao;
public PetDao getPetDao() {
return petDao;
}
public void setPetDao(PetDao petDao) {
this.petDao = petDao;
}
#RequestMapping(method = RequestMethod.GET)
public List<Pet> getAllPets() throws IOException {
getLog().info("Rest Controller activating........");
List<Pet> petList = getPetDao().getAllPets();
return petList;
}
}
And here is my Pet entity class:
package mywebapp.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Date;
import java.util.Set;
#Entity
#Table(name = "pet")
public class Pet {
private int petId;
private String name;
private String owner;
private String species;
private String sex;
private Date birth;
private Date death;
private Set<Toy> toys;
#Id
#Column(name = "pet_id")
#GeneratedValue
#JsonProperty(value="pet_id",required=true)
public int getId() {
return petId;
}
public void setId(int id) {
this.petId = id;
}
#JsonProperty(value="pet_name",required=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public String getSpecies() {
return species;
}
public void setSpecies(String species) {
this.species = species;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public Date getDeath() {
return death;
}
public void setDeath(Date death) {
this.death = death;
}
#OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER,targetEntity=Toy.class, mappedBy="pet")
public Set<Toy> getToys() {
return toys;
}
public void setToys(Set<Toy> toys) {
this.toys = toys;
}
}
Anyone knows what's going on here? Any hint will be appreciated, lots of thanks in advance!
Jackson 2.7 is not supported by Spring 4.2 - it will be in 4.3+.
Check out the library requirements for Spring on the Spring wiki and see SPR-13728 and SPR-13483.