Query Creation Spring Data JPA - java

I have a bunch of Car Objects. I'm able to render a list of all the Car Objects with each field being displayed on list.html. If I just wanted to display a list of make values on list.html, how would I go about that by using a query? Looking in Spring Data JPA Docs section 5.3.2, could I do something like findByAllMake();?
I've tried findByAllMake();...
The below code shows how I am successfully getting a complete list of all the objects. Looking to just get a list of all makes.
Car.java
package com.example.demo;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Car {
#Id
private String id;
private String make;
private String model;
private String year;
public Car() {
}
public Car(String id, String make, String model, String year) {
this.id = id;
this.make = make;
this.model = model;
this.year = year;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
}
CarController.java :
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
#Controller
public class CarController {
#Autowired
private CarRepository carRepository;
#GetMapping("/list")
public String carMakeList(Model model){
model.addAttribute("list", carRepository.getAllMakes());
return "list";
}
}
CarRepository.java
package com.example.demo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface CarRepository extends JpaRepository<Car, String> {
#Query(value="SELECT * FROM car;", nativeQuery=true)
List<Car> getAllMakes();
}
I've tried findByAllMake(); but I get back an Unsatisfactory Dependency error.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'carController': Unsatisfied dependency expressed through field 'carService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'carService': Unsatisfied dependency expressed through field 'carRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'carRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.example.demo.CarRepository.findAllByMake()! No parameter available for part make SIMPLE_PROPERTY (1): [Is, Equals] NEVER.

Makes are Strings. So if you want your method to return a list of makes, its return type should be List<String>, not List<Car>.
And the query needs to select makes, not cars:
select distinct car.make from Car car

Haven't run this on my laptop but what if you try:
to add constructor to CarController:
public CarController(CarRepository carRepository){
this.carRepository = carRepository;
}
And then probably just try:
public List<Car> findAll();
in the repository?

Related

Hibernate Error : attempted to assign id from null one-to-one property. Why?

I am trying my hands at Hibernate Relation Mapping(OneToOne, etc) exercises using Spring Boot. Before you ask, I have already consulted this link : [https://stackoverflow.com/questions/11104897/hibernate-attempted-to-assign-id-from-null-one-to-one-property-employee]. I understand that the weak entity needs to have a ref to the parent entity, but I am not able to figure out, why I need to do that explicitly in Person class constructor?
The Codes are as follows.
SpringApplication:
package com.OneToOne.OneToOneMappingPractice;
import java.util.Arrays;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
#SpringBootApplication
public class App
{
public static void main( String[] args )
{
ApplicationContext applContext = SpringApplication.run(App.class, args);
String[] beanNames = applContext.getBeanDefinitionNames();
Arrays.sort(beanNames);
for(String beanName : beanNames)
System.out.println(beanName);
}
}
CRUDController.java:
package com.OneToOne.OneToOneMappingPractice;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
#CrossOrigin
public class CRUDController
{
private static int randomNumber=(int) Math.random();
#Autowired
private CRUDControllerRepository repository;
#GetMapping(value="/add")
public void add()
{
Person person = new Person("Person"+randomNumber, "Street"+randomNumber, randomNumber);
repository.save(person);
randomNumber+=1;
}
#GetMapping(value="/getAll")
public List<Person> getAll()
{
return repository.findAll();
}
#DeleteMapping(value="/deleteAll")
public void deleteAll()
{
repository.deleteAll();
}
}
Person.java:
package com.OneToOne.OneToOneMappingPractice;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
#Entity
public class Person
{
private String name;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "user_id")
private int Id;
#OneToOne(mappedBy="person", cascade = CascadeType.ALL)
#PrimaryKeyJoinColumn
private Address address;
public Person() {}
public Person(String name, String streetName, int house_number)
{
super();
this.name = name;
this.address=new Address();
this.address.setStreetName(streetName);
this.address.setHouse_number(house_number);
//this.address.setPerson(this);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
Address.java:
package com.OneToOne.OneToOneMappingPractice;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.OneToOne;
#Entity
public class Address {
#Id
#Column(name="user_id")
private int Id;
private int house_number;
private String streetName;
#OneToOne
#MapsId
#JoinColumn(name = "user_id")
private Person person;
public Address(){}
public int getHouse_number() {
return house_number;
}
public void setHouse_number(int house_number) {
this.house_number = house_number;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
// public Person getPerson() {
// return person;
// }
public void setPerson(Person person) {
this.person = person;
}
}
CRUDControllerRepository.java:
package com.OneToOne.OneToOneMappingPractice;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
#Repository
#Transactional
public interface CRUDControllerRepository extends JpaRepository<Person, Integer>
{
Person save(Person person);
void deleteAll();
List<Person> findAll();
}
Following are my questions :
As you can see, in the Person class parameterized constructor, I have commented out the line : this.address.setPerson(this);. If I keep this line commented out, I get the exception : "attempted to assign id from null one-to-one property [com.OneToOne.OneToOneMappingPractice.Address.person]; nested exception is org.hibernate.id.IdentifierGenerationException: attempted to assign id from null one-to-one property [com.OneToOne.OneToOneMappingPractice.Address.person]". If I remove the comment syntax, it works perfectly. Why do I need to explicitly do this? Isn't the #OneToOne annotation supposed to take care of these references by itself?
2.If I enable the Person getPerson() method in the Address class, it recursively goes on, until the stack explodes: "Cannot render error page for request [/getAll] and exception [Could not write JSON: Infinite recursion (StackOverflowError); nested exception is com.fasterxml.jackson.databind.JsonMappingException".
Why cant Hibernate itself determine that it needs to stop at that boundary itself, instead of fetching the Parent Object again?
Am I missing something here about these mapping annotations, or anything else?
1- As you can see, in the Person class parameterized constructor, I
have commented out the line : this.address.setPerson(this);. If I keep
this line commented out, I get the exception : "attempted to assign id
from null one-to-one property
Hibernate will not set it explicitly because it does not know to which person this address belongs to you need to specify that explicitly.
The purpose of #OneToOne is to tell hibernate where to get the rest of the data when it is already mapped.
2.If I enable the Person getPerson() method in the Address class, it recursively goes on, until the stack explodes: "Cannot render error
page for request [/getAll] and exception [Could not write JSON:
Infinite recursion (StackOverflowError); nested exception is
com.fasterxml.jackson.databind.JsonMappingException". Why cant
Hibernate itself determine that it needs to stop at that boundary
itself, instead of fetching the Parent Object again?
The exception is caused by Jackson serializer and not from hibernate.
you can look at the examples here to see how it is fixed https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion.

How can I reach database as json value when i request on my local browser?

Note: This is a project which has a connection with database on other tables. I just made a new table, but i must have something wrong in my codes, because i cant get what i want.
I have a City table, and this table has 3 columns, named id, name, city_id. And i imported a csv file, so when i query, I can see some data.
I wrote Entity, Repository, Controller, and Service, in Java on Eclipse
What should I do? For example, when i search like localhost:8181/mfc/city/getAllCities that should give me all the cities as json
Could you tell me what i should add?
City.java
package com.mfc.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="city")
public class City{
#Id
#Column(name="id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
int id;
#Column(name="city_name")
String cityName;
#Column(name="city_id")
int cityId;
public City() {
super();
}
public City(int id, String cityName, int cityId) {
super();
this.id = id;
this.cityName = cityName;
this.cityId = cityId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
}
CityController.java
package com.mfc.admin.controller;
import java.util.List;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
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.annotation.RestController;
import com.mfc.admin.service.CityService;
import com.mfc.entity.City;
#RestController
#RequestMapping("/city")
public class CityController {
private static final Logger logger = LogManager.getLogger(CityController.class);
#Autowired
CityService cityService;
#RequestMapping(value="/getAllCities", method=RequestMethod.GET, headers = "Accept=application/json")
public List getCities() {
logger.trace("CityController: getAllCities begins");
List listOfCities = cityService.getAllCities();
logger.trace("CityController: getAllCities ends");
return listOfCities;
}
#RequestMapping(value="/getCity/{id}", method=RequestMethod.GET, headers = "Accept=application/json")
public City getCityById(#PathVariable int id) {
return cityService.getCity(id);
}
}
CityService.java
package com.mfc.admin.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.mfc.entity.City;
import com.mfc.repository.CityRepository;
#Service("cityService")
public class CityService {
#Autowired
CityRepository cityDTO;
#Transactional
public List getAllCities() {
return cityDTO.getAllCities();
}
#Transactional
public City getCity(int id) {
return cityDTO.getCity(id); // getCity is red here, there is mistake i guess
}
}
CityRepository.java
package com.mfc.repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.mfc.entity.City;
public interface CityRepository extends JpaRepository<City, Integer>{
List getAllCities();
City getCity();
}
In the CityService you call the CityRepository like this
return cityDTO.getCity(id); // getCity is red here, there is mistake i guess
But no such method is defined in the CityRepository. Try using this line return cityDTO.findById(id).get();
You can't see the method findById(Integer id) in the CityRepository, but it is there, because the CityRepository extends JpaRepository<City, Integer>. Find some Spring Data tutorial to know what's really going on in here, long story short the Spring Data is able to generate a lot of standard methods for you.
The method cityDTO.findById(id) returns Optional<City>, not City. To get the instance of City, just add '.get()' method, as it is in the example. It should work for you if city exists in the database. For proper work with Optional find some tutorial. It is a wrapper of an object that may or may not be present, detailed explanation is out of the scope of this answer.
maybe you can try to set up message converter manualy, google MappingJackson2HttpMessageConverter and you'll know what to do.

Consume java spring rest api and insert records to mysql table

I am trying to consume a spring rest API and store the results into a staging table.
Here is what I tried. I am very new to java and spring, please forgive my mistakes.
My staging table name "greetingsstaging".
I am new to spring development, please help in understanding the issue.
I am using JPA and spring.
This is the main application.
package com.javatechie.spring.api;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.javatechie.spring.api.entty.Greetings;
import com.javatechie.spring.api.service.Greet;
import com.javatechie.spring.api.service.GreetInterface;
import com.javatechie.spring.api.service.GreetingsService;
#SpringBootApplication
public class GreetingsConsumerApplication {
private static RestTemplate rs = new RestTemplate();
private static String baseUrl = "http://localhost:8080/api/Greetings";
private static GreetInterface greetInterface;
#Autowired
public GreetingsConsumerApplication(GreetInterface theGreetInterface) {
greetInterface = theGreetInterface;
}
public static void main(String[] args) {
SpringApplication.run(GreetingsConsumerApplication.class, args);
ResponseEntity<List<GreetingsService>> response = rs.exchange(baseUrl, HttpMethod.GET, null,
new ParameterizedTypeReference<List<GreetingsService>>() {
});
List<GreetingsService> gs = response.getBody();
for (GreetingsService g : gs) {
Greetings greetings = new Greetings(g.getId(), g.getName(), g.getAge(), g.getAddress());
System.out.println("Id : " + greetings.getId() + " name : " + greetings.getName() + " Age : "
+ greetings.getAge() + " Address : " + greetings.getAddress());
greetInterface.save(greetings);
}
}
}
Here is my service.
package com.javatechie.spring.api.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import com.javatechie.spring.api.entty.Greetings;
import com.javatechie.spring.api.repository.GreetingsRepository;
#Service
public class Greet implements GreetInterface{
private GreetingsRepository repo;
#Autowired
public Greet(GreetingsRepository repo) {
super();
this.repo = repo;
}
#Override
public void save(Greetings obj) {
repo.save(obj);
}
}
Here is the repository interface.
package com.javatechie.spring.api.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.javatechie.spring.api.entty.Greetings;
#Repository
public interface GreetingsRepository extends JpaRepository<Greetings, Integer> {
}
Here is my pojo class.
package com.javatechie.spring.api.entty;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="greetingsstaging")
public class Greetings {
int id;
String name;
int age;
String address;
public Greetings(int id, String name, int age, String address) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
}
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
#Override
public String toString() {
return "Greetings [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
}
}
I am getting following exception.
Error creating bean with name 'requestMappingHandlerAdapter' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Unsatisfied dependency expressed through method 'requestMappingHandlerAdapter' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mvcConversionService' defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/WebMvcAutoConfiguration$EnableWebMvcConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.format.support.FormattingConversionService]: Factory method 'mvcConversionService' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'greetingsRepository' defined in com.javatechie.spring.api.repository.GreetingsRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot resolve reference to bean 'jpaMappingContext' while setting bean property 'mappingContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.javatechie.spring.api.entty.Greetings
My main idea is to store the results from API into a staging table.
You're missing #Id annotation of Greetings class. Each JPA entity must have a primary key which uniquely identifies it.
#Entity
#Table(name="greetingsstaging")
public class Greetings {
#Id
int id;
}

How can I make Autowired adnotation working?

I'm trying to learn spring using some internet courses. I have problem with #Autowired and I'm still getting Error: org.springframework.beans.factory.UnsatisfiedDependencyException
I have found many similar problems, but no one suits mine.
My Product class:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table
public class Product {
#Id
private int id;
private String name;
#Column(name = "description")
private String desc;
private double price;
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;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Interface ProductRepository:
import HIB_UD_01.product.entities.Product;
import org.springframework.data.repository.CrudRepository;
public interface ProductRepository extends CrudRepository<Product, Integer> {
}
ProductdataApplication:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ProductdataApplication {
public static void main(String[] args) {
SpringApplication.run(ProductdataApplication.class, args);
}
}
And my Test class:
import HIB_UD_01.product.entities.Product;
import HIB_UD_01.product.repos.ProductRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
#RunWith(SpringRunner.class)
#SpringBootTest
public class ProductdataApplicationTests {
#Autowired
ProductRepository repository;
#Test
public void contextLoads() {
}
#Test
public void testCreate() {
Product product = new Product();
product.setId(1);
product.setName("Iphone");
product.setDesc("Awesome");
product.setPrice(1000d);
repository.save(product);
}
}
And last,my properites file:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password
I should put data about product into db, but I get an error:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'HIB_UD_01.product.ProductdataApplicationTests': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'HIB_UD_01.product.repos.ProductRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
You probably have to enable repositories on your SpringBootApplication class (or in a separate configuration class):
https://www.concretepage.com/spring-boot/spring-boot-crudrepository-example
If that doesn't work, make sure your SpringBootApplication class is a package higher then the rest of your classes, so SpringBoot can autodetect your beans. (And you can try to annotate your repository with #Repository then, to make sure SpringBoot autodetects your repository.)
Also see:
https://dzone.com/articles/the-springbootapplication-annotation-example-in-ja
https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-structuring-your-code.html
OK, problem fixed. I added #Repository to ProductRepository. I cleared repository folder and download new fresh repositories.
Then I have error with time zone in connection to MySQL. So I edit my properities file:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
Thank you for your help!

No property lastname found for type User (JPA)

User.java:
package com.hodor.booking.jpa.domain;
import javax.persistence.Entity;
import java.util.Date;
#Entity
public class User extends AbstractPersistable {
private String firstName;
private String lastName;
private String email;
private Date birthday;
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public String getEmail() {
return email;
}
public Date getBirthday() {
return birthday;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public void setEmail(String email) {
this.email = email;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
UserRepository.java:
package com.hodor.booking.jpa.repository;
import com.hodor.booking.jpa.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* For Spring Data JPA query methods see:
* http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
*/
public interface UserRepository extends JpaRepository<User, Long> {
public User findByEmail(String email);
public User findByLastname(String lastName);
}
UserService.java:
package com.hodor.booking.service;
import com.hodor.booking.jpa.domain.User;
import com.hodor.booking.jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.util.List;
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public User saveUser(User user) {
Assert.notNull(user);
return userRepository.saveAndFlush(user);
}
public List<User> findAll() {
return userRepository.findAll();
}
public User findOne(Long id) {
Assert.notNull(id);
return userRepository.findOne(id);
}
public User findByEmail(String email) {
Assert.hasLength(email);
return userRepository.findByEmail(email);
}
public User findByLastname(String lastName) {
Assert.hasLength(lastName);
return userRepository.findByLastname(lastName);
}
}
UserController:
package com.hodor.booking.controller;
import com.hodor.booking.jpa.domain.User;
import com.hodor.booking.service.UserService;
import com.wordnik.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("/api/v1/users")
#Api(value = "users", description = "User resource endpoint")
public class UserController {
private static final Logger log = LoggerFactory.getLogger(UserController.class);
#Autowired
private UserService userService;
#RequestMapping(method = RequestMethod.GET)
public List<User> index() {
log.debug("Getting all users");
return userService.findAll();
}
#RequestMapping(value = "/{id}", method = RequestMethod.GET)
public User get(#PathVariable("id") Long id) {
return userService.findOne(id);
}
#RequestMapping(value = "/{lastName}", method = RequestMethod.GET)
public User get(#PathVariable("lastName") String lastName) {
return userService.findByLastname(lastName);
}
}
StackTrace:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.hodor.booking.jpa.repository.UserRepository com.hodor.booking.service.UserService.userRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property lastname found for type User!
Problem:
I added the findByLastname Method and I can't find the problem (I am new to this).
I had never used Spring... but reading the docs about org.springframework.data.jpa.repository.JpaRepository, I suggest to rename your method: findByLastname as findByLastName in the UserRepository interface...
It seems this functionalty generates JPA queries by reading and parsing the defined methods at a given interface that extends from JpaRepository ... and by saying "findByLastname", Spring expects to find a property at User Entity as: lastname and not lastName

Categories