Hibernate / Spring boot: when I update a product, I successfully update the variable I want to modify but the image disappears (which is of type blob) - spring-boot

I am trying to update a product in Postman by changing only the name; when I do this, the name is updated successfully but I notice that the product photo (blob type) that was previously saved when the object was inserted disappears (it is automatically set to null).
How can I solve this problem?
Thank you all
Product.java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;
import Model.Product;
#Entity
#Table(name="product")
public class Product {
#Id
private String prodcode;
private String name;
#Lob
private byte[] photo;
public Product() {
}
public Product(String prodcode, String name, byte[] photo) {
this.prodcode = prodcode;
this.name = name;
this.photo = photo;
}
public String getProdcode() {
return prodcode;
}
public void setProdcode(String prodcode) {
this.prodcode = prodcode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(byte[] photo) {
this.photo = photo;
}
Product_DAO_Imp.java
package DAO;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import Model.Product;
#Repository
public class Product_DAO_Imp implements Product_DAO{
#Autowired
private SessionFactory sessionFactory;
#Override
public boolean updateProduct(Product product) {
boolean status=false;
try {
sessionFactory.getCurrentSession().update(product);
status=true;
} catch (Exception e) {
e.printStackTrace();
}
return status;
}
// ....
// ....
// ....
}
Product_Service_Imp
package Service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import DAO.Product_DAO;
import Model.Product;
#Service
#Transactional
public class Product_Service_Imp implements Product_Service {
#Autowired
private Product_DAO productdao;
#Override
public boolean updateProduct(Product product) {
return productdao.updateProduct(product);
}
// ....
// ....
// ....
}
Controller.java
import java.io.IOException;
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.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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import Model.Product;
import Service.Product_Service;
#RestController
#CrossOrigin(origins="http://localhost:4200")
#RequestMapping(value="/api")
public class Controller {
#Autowired
private Product_Service productservice;
#PostMapping("update-product/{prodcode}")
public boolean updateProduct(#RequestBody Product product,#PathVariable("prodcode") String prodcode) {
product.setProdcode(prodcode);
return productservice.updateProduct(product);
}
// ....
// ....
// ....
}

You can follow load and save approach to do the desired
It follows below steps
Read the row from DB, using prodcode
update the fields in the above read object and update
You can update the below method in the your Product_DAO_Imp.java
#Override
public boolean updateProduct(Product product) {
boolean status=false;
try {
Product productFrmDb = sessionFactory.getCurrentSession().get(Product.class,product.getProdcode());
productFrmDb.setName(product.getName());
sessionFactory.getCurrentSession().update(productFrmDb);
status=true;
} catch (Exception e) {
e.printStackTrace();
}
return status;
}

Related

Custom Exception not thrown in controller-method when no data is found in database

My controller always give Internal server error whenever my condition fail, and are suppose to throw custom exception ResourceNotFoundException.
When I call account/1-endpoint (no account with id 1 in database) I expect an ResourceNotFoundException, but instead I get Internal server Error.. I do not understand why ResourceNotFoundException is not thrown, I watched several youtube tutorials on the topic.
Please help by providing possible solutions.
My model classes are
package com.bank2.Model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import org.hibernate.annotations.Proxy;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#javax.persistence.Table(name="Account")
#Proxy(lazy = false)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Account {
#Id
int accountNumber;
#Column(name="balance")
Double balance;
#Column(name="accountType")
String accountType;
public Account() {
super();
}
#Override
public String toString() {
return "Account [accountNumber=" + accountNumber + ", balance=" + balance + ", accountType=" + accountType + "]";
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public Double getBalance() {
return balance;
}
public void setBalance(Double balance) {
this.balance = balance;
}
public String getAccountType() {
return accountType;
}
public void setAccountType(String accountType) {
this.accountType = accountType;
}
public Account(int accountNumber, Double balance, String accountType) {
super();
this.accountNumber = accountNumber;
this.balance = balance;
this.accountType = accountType;
}
}
package com.bank2.Model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Proxy;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
#Entity
#Table(name="Customer")
#Proxy(lazy = false)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
Integer customerId;
#Column(name="customerName")
String customerName;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL,targetEntity = Account.class)
#JoinColumn(name = "ca_fk",referencedColumnName ="customerId")
private List<Account> accounts;
public Customer() {
super();
}
public Customer(Integer customerId, String customerName, List<Account> accounts) {
super();
this.customerId = customerId;
this.customerName = customerName;
this.accounts = accounts;
}
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public List<Account> getAccount() {
return accounts;
}
public void setAccount(List<Account> accounts) {
this.accounts = accounts;
}
#Override
public String toString() {
return "Customer [customerId=" + customerId + ", customerName=" + customerName + ", accounts=" + accounts + "]";
}
}
My service classes are
package com.bank2.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bank2.Model.Customer;
import com.bank2.repository.CustomerRepository;
#Service
public class CustomerService {
#Autowired
CustomerRepository customerRepository;
public Customer customerCreate(Customer customer) {
Customer x= customerRepository.save(customer);
return x;
}
}
package com.bank2.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bank2.Model.Account;
import com.bank2.repository.AccountRepository;
#Service
public class AccountService {
#Autowired
AccountRepository accountRepository;
public Account findAccountById(int accountNumber) {
return accountRepository.getById(accountNumber);
}
}
my controller class are
package com.bank2.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bank2.Exception.ResourceNotFoundException;
import com.bank2.Model.Account;
import com.bank2.ServiceImpl.AccountService;
#RestController
#RequestMapping("/account")
public class AccountController {
#Autowired
AccountService accountService;
#GetMapping("/{accountNumber}")
public ResponseEntity<?> getAccountById(#PathVariable("accountNumber") int accountNumber){
Account acc=accountService.findAccountById(accountNumber);
if(acc==null) {
throw new ResourceNotFoundException("Account [accountNumber="+accountNumber+"] can't be found");
}else {
return new ResponseEntity<>(acc,HttpStatus.FOUND);
}
}
package com.bank2.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
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.bank2.Exception.ResourceNotFoundException;
import com.bank2.Model.Customer;
import com.bank2.ServiceImpl.CustomerService;
#RestController
#RequestMapping("/customer")
public class CustomerController {
#Autowired
CustomerService customerService;
#PostMapping("/createCust")
public ResponseEntity<?> CreateCustomer(#RequestBody Customer customer){
Customer cus=customerService.customerCreate(customer);
Optional<Customer> cus1 = Optional.ofNullable(cus);
if(cus1.isEmpty()) {
throw new ResourceNotFoundException("customer not created!!");
}else {
return new ResponseEntity<>(cus,HttpStatus.CREATED);
}
}
}
my expection classes are
package com.bank2.Exception;
import java.time.LocalDateTime;
import java.util.List;
import org.springframework.http.HttpStatus;
public class ApiErrors {
String message;
List<String> details;
HttpStatus status;
LocalDateTime timestamp;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<String> getDetails() {
return details;
}
public void setDetails(List<String> details) {
this.details = details;
}
public HttpStatus getStatus() {
return status;
}
public void setStatus(HttpStatus status) {
this.status = status;
}
public LocalDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(LocalDateTime timestamp) {
this.timestamp = timestamp;
}
public ApiErrors() {
super();
// TODO Auto-generated constructor stub
}
public ApiErrors(String message, List<String> details, HttpStatus status, LocalDateTime timestamp) {
super();
this.message = message;
this.details = details;
this.status = status;
this.timestamp = timestamp;
}
#Override
public String toString() {
return "ApiErrors [message=" + message + ", details=" + details + ", status=" + status + ", timestamp="
+ timestamp + "]";
}
}
package com.bank2.Exception;
public class ResourceNotFoundException extends RuntimeException{
/**
*
*/
private static final long serialVersionUID = 1L;
public ResourceNotFoundException() {
super();
}
public ResourceNotFoundException(String message) {
super(message);
}
}
package com.bank2.Exception;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
#ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<Object> handleResourceNotFoundException(ResourceNotFoundException ex){
String msg=ex.getMessage();
List<String> details=new ArrayList<>();
details.add("Resource not found");
ApiErrors errors=new ApiErrors(msg,details,HttpStatus.BAD_REQUEST,LocalDateTime.now());
return new ResponseEntity<Object>(errors,HttpStatus.BAD_REQUEST);
}
#ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleOther(Exception ex){
String msg=ex.getMessage();
List<String> details=new ArrayList<>();
details.add("Other Exceptions");
ApiErrors errors=new ApiErrors(msg,details,HttpStatus.INTERNAL_SERVER_ERROR,LocalDateTime.now());
return new ResponseEntity<Object>(errors,HttpStatus.INTERNAL_SERVER_ERROR);
}
}
This is the Internal server error I have gotten so far in Postman:
{
"message": "Unable to find com.bank2.Model.Account with id 1; nested exception is javax.persistence.EntityNotFoundException: Unable to find com.bank2.Model.Account with id 1",
"details": [
"Other Exceptions"
],
"status": "INTERNAL_SERVER_ERROR",
"timestamp": "2022-04-02T22:09:28.0486246"
}
My repositories are
'''
package com.bank2.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.bank2.Model.Account;
#Repository
public interface AccountRepository extends JpaRepository<Account, Integer> {
}
'''
'''
package com.bank2.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.bank2.Model.Customer;
#Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {
}
'''
From the Documentation JpaRepository.html#getById-ID-
T getById(ID id)
Returns a reference to the entity with the
given identifier. Depending on how the JPA persistence provider is
implemented this is very likely to always return an instance and throw
an EntityNotFoundException on first access. Some of them will reject
invalid identifiers immediately.
The error message you get shows ...nested exception is EntityNotFoundException, so that could be normal...
So you could throw a ResourceNotFoundException in your service when the Account is not found.
#Service
public class AccountService {
public Account findAccountById(int accountNumber) {
try {
return accountRepository.getById(accountNumber);
} catch(EntityNotFoundException e) {
throw new ResourceNotFoundException("Account [accountNumber="+accountNumber+"] can't be found")
}
}

How can I implement rsockets to a project with R2DBC in Spring?

I am doing a notifications project with reactive websockets / rsockets in Spring and Vue. But I have not been able to bind my ws to the database. I'm stuck, I need help.
This is my Entity (ProductDto and ProductRequestDto are the same syntax)
package com.example.productservice.entity;
import org.springframework.data.annotation.Id;
import lombok.Data;
import lombok.ToString;
#Data
#ToString
public class Products {
#Id
private Integer id;
private String description;
private Integer price;
private String subscriber;
public Products() {
}
//Getters And Setters
}
This is my repository
package com.example.productservice.repository;
import org.springframework.data.r2dbc.repository.Query;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
import org.springframework.stereotype.Repository;
import com.example.productservice.entity.Products;
import reactor.core.publisher.Mono;
#Repository
public interface ProductRepository extends ReactiveCrudRepository<Products, Integer> {
#Query //Example of Query (Ignore this)
("insert into products values (null, :product, :price, :subscriber)")
Mono<Boolean> insert (String product, int price, String subscriber);
}
this is my service (I leave the complete code because I think it can be useful to someone)
package com.example.productservice.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.productservice.dto.ProductDto;
import com.example.productservice.repository.ProductRepository;
import com.example.productservice.util.EntityDtoUtil;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.publisher.Sinks;
#Service
public class ProductService {
#Autowired
private ProductRepository repository;
public Flux<ProductDto> getAll(){
return this.repository.findAll()
.map(EntityDtoUtil::toDto);
}
public Mono<ProductDto> getProductById(final int id){
return this.repository.findById(id)
.map(EntityDtoUtil::toDto);
}
public Mono<ProductDto> insertProduct(Mono<ProductDto> productDtoMono){
return productDtoMono
.map(EntityDtoUtil::toEntity)
.flatMap(this.repository::save)
.map(EntityDtoUtil::toDto);
}
public Mono<ProductDto> updateProduct(int id, Mono<ProductDto> productDtoMono){
return this.repository.findById(id)
.flatMap(p -> productDtoMono
.map(EntityDtoUtil::toEntity)
.doOnNext(e -> e.setId(id)))
.flatMap(this.repository::save)
.map(EntityDtoUtil::toDto);
}
public Mono<Void> deleteProduct (int id) {
return this.repository.deleteById(id);
}
}
and this is my Controller
package com.example.productservice.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
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.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.example.productservice.dto.ProductDto;
import com.example.productservice.service.ProductService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
#RestController
#RequestMapping("product")
#CrossOrigin(origins= "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class ProductController {
#Autowired
private ProductService service;
#GetMapping("all")
public Flux<ProductDto> all(){
return this.service.getAll();
}
#GetMapping("{id}")
public Mono<ResponseEntity<ProductDto>> getProductById(int id){
return this.service.getProductById(id)
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.notFound().build());
}
#PostMapping
public Mono<ProductDto> insertProductTable(#RequestBody Mono<ProductDto> productDtoMono){
return this.service.insertProduct(productDtoMono);
}
#PutMapping("{id}")
public Mono<ResponseEntity<ProductDto>> updateProduct(#PathVariable int id, #RequestBody Mono<ProductDto> productMonoDto) {
return this.service.updateProduct(id, productMonoDto)
.map(ResponseEntity::ok)
.defaultIfEmpty(ResponseEntity.notFound().build());
}
#DeleteMapping
public Mono<Void> deleteProduct(#PathVariable int id){
return this.service.deleteProduct(id);
}
}
So far is my original code functional in the traditional way. I have tried ways to implement rsockets that I leave here:
my applicattion.properties in server side
spring.rsocket.server.port=7000
spring.rsocket.server.transport=tcp
spring.r2dbc.url=r2dbc:mysql://localhost:3306/people2?options=DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
spring.r2dbc.username=root
spring.r2dbc.password=
Modification in ProductService
#Service
public class ProductService {
#Autowired
private ProductRepository repository;
#Autowired
//private Sinks.Many<ProductDto> sink;
#MessageMapping("repository.findAll")
public Flux<ProductDto> getAll(){
return this.repository.findAll()
.map(EntityDtoUtil::toDto);
}
Modification in ProductController client side
#RestController
#RequestMapping("product")
#CrossOrigin(origins= "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class ProductController {
#Autowired
private ProductService service;
private RSocketRequester requester;
#GetMapping("all")
public Flux<ProductDto> all(){
this.requester.route("post.findAll")
.retrieveFlux(ProductDto.class);
return this.service.getAll();
}

Spring boot controller not getting scanned error 404 not found

I am trying to create restful api but my controller is not working and I'm getting the error shown below:
{
"timestamp": "2020-06-11T15:28:18.103+00:00",
"status": 404,
"error": "Not Found",
"message": "",
"path": "/path/findCarsAfterYear/2020"
}
Please help me to resolve this.
Entity Class
package com.example.demo.data;
import javax.persistence.*;
#Entity
public class Car {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private long id;
#Column
private String model;
#Column
private Integer year;
// standard getters and setters
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
}
Repository Class
package com.example.demo.Repository;
import com.example.demo.data.Car;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.query.Procedure;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface CarRepository extends JpaRepository<Car, Integer> {
#Query("Select wds from Car wds where year=?1 ")
List<Car> findCarsAfterYear(Integer year);
}
Service class
package com.example.demo.service;
import com.example.demo.Repository.CarRepository;
import com.example.demo.data.Car;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
#Service
public class CarService {
#Autowired
CarRepository carRepository;
public List<Car> findCarsAfterYear(Integer id) {
return carRepository.findCarsAfterYear(id);
}
}
Controller class
package com.example.demo.Controller;
import com.example.demo.data.Car;
import com.example.demo.service.CarService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#Controller
#RequestMapping(path="/test")
public class CarController {
#Autowired(required=true)
private CarService carService;
#GetMapping(value="/findCarsAfterYear/{id}")
public List<Car> findCarsAfterYear(Integer id) {
return carService.findCarsAfterYear(id);
}
}
Application Class
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#Configuration
#SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
#EnableJpaRepositories("com.example.demo.Repository")
#EntityScan("com.example.demo.data")
#ComponentScan(basePackages="com.example.demo.service,com.example.demo.Controller")
#EnableCaching
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
In you want to use #Controller then you have to provide #ResponseBody explicitly.
#Controller
#RequestMapping(path="/test")
public class CarController {
#Autowired(required=true)
private CarService carService;
#GetMapping(value="/findCarsAfterYear/{id}")
#ResponseBody
public List<Car> findCarsAfterYear(Integer id) {
return carService.findCarsAfterYear(id);
}
}
But in case #RestController, which is combination of #Controllerand #ResponseBody
#RestController
#RequestMapping(path="/test")
public class CarController {
#Autowired(required=true)
private CarService carService;
#GetMapping(value="/findCarsAfterYear/{id}")
public List<Car> findCarsAfterYear(Integer id) {
return carService.findCarsAfterYear(id);
}
}
I hope this will be helpful.

Error: Action : Consider defining a bean of type "package" in your configuration

the following error I am getting :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field employeeDAO in com.example.demo.controller.EmployeeController required a bean of type 'com.example.demo.dao.EmployeeDAO' that could not be found.
Action:
Consider defining a bean of type 'com.example.demo.dao.EmployeeDAO' in your configuration.
my folder structure:
below are the files:
1.
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
#SpringBootApplication
#EnableJpaRepositories
public class RestCrudDemo1Application {
public static void main(String[] args) {
SpringApplication.run(RestCrudDemo1Application.class, args);
}
}
2.
package com.example.demo.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.dao.EmployeeDAO;
import com.example.demo.model.Employee;
#RestController
#RequestMapping("/company")
public class EmployeeController {
#Autowired
EmployeeDAO employeeDAO;
#PostMapping ("/employee")
public Employee createEmployee(#Valid #RequestBody Employee emp){
return employeeDAO.save(emp);
}
#GetMapping ("/findAll")
public List<Employee> findAll(){
return employeeDAO.findAll();
}
#GetMapping("/employees/{id}")
public ResponseEntity<Employee> getEmployeeById(#PathVariable(value = "id") Long empid){
Employee emp = employeeDAO.findOne(empid);
if (emp==null){
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok().body(emp);
}
#PutMapping("/employees/{id}")
public ResponseEntity<Employee> updateEmployee(#PathVariable(value = "id") Long empid, #Valid #RequestBody Employee empDetails){
Employee emp = employeeDAO.findOne(empid);
if (emp==null){
return ResponseEntity.notFound().build();
}
emp.setName(empDetails.getName());
emp.setDesignation(empDetails.getExpertise());
emp.setExpertise(empDetails.getExpertise());
Employee updateEmployee = employeeDAO.save(emp);
return ResponseEntity.ok().body(updateEmployee);
}
#DeleteMapping("/employees/{id}")
public ResponseEntity<Employee> deleteEmployee(#PathVariable(value = "id") Long empid){
Employee emp = employeeDAO.findOne(empid);
if (emp==null){
return ResponseEntity.notFound().build();
}
employeeDAO.delete(emp);
return ResponseEntity.ok().build();
}
}
3.
package com.example.demo.dao;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.demo.model.Employee;
import com.example.demo.repository.EmployeeRepository;
public class EmployeeDAO {
#Autowired
EmployeeRepository employeeRepository;
public Employee save(Employee emp){
return employeeRepository.save(emp);
}
public List<Employee> findAll(){
return employeeRepository.findAll();
}
public Employee findOne(Long empid){
return employeeRepository.findOne(empid);
}
public void delete(Employee emp){
employeeRepository.delete(emp);
}
}
4.
package com.example.demo.model;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotBlank;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
#Entity
#Table(name = "Employees")
#EntityListeners(AuditingEntityListener.class)
public class Employee {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long Id;
#NotBlank
private String name;
#NotBlank
private String designation;
#NotBlank
private String expertise;
#NotBlank
#Temporal(TemporalType.TIMESTAMP)
#LastModifiedDate
private Date createdAt;
public long getId() {
return Id;
}
public void setId(long id) {
Id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getExpertise() {
return expertise;
}
public void setExpertise(String expertise) {
this.expertise = expertise;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
}
5.
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.model.Employee;
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
public Employee findOne(Long empid);
}
From the error, I get to know that employee dao bean has not been created for autowiring into the controller.
By analysing your employee dao class, you forgot to annotate with #Repository due to which bean has not been created by context scanning.
Annotate empoyeedao class with #Repository. It should solve your problem.

Error creating bean, Injection of autowired dependencies failed - 500 Internal Server Error

I have created a new Spring project and I have some trouble when I run the application. I am new to Spring development and I thing that the annotations are not placed properly. Any detailed explanation would be great for me for better understating. I am currently reading Spring in action, but if any other book or tutorial seems more accurate, please leave me a comment :)[this is the error that I am getting - 500 Internal Server Error].
This is my project:
HelloWorldConfiguration
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#EnableWebMvc
#ComponentScan(basePackages = "com.websystique.springmvc")
public class HelloWorldConfiguration {
#Bean(name="HelloWorld")
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
HelloWordInitializer
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class HelloWorldInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(HelloWorldConfiguration.class);
ctx.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet(
"dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
HelloWorldController
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import service.StudentService;
import java.util.HashMap;
import java.util.Map;
#Configuration
#Controller
#ComponentScan(basePackages = "com.websystique.springmvc")
#RequestMapping("/")
public class HelloWorldController {
public HelloWorldController(){
}
#Autowired
private StudentService studentService;
private Map<String, Student> persoaneAdaugate = new HashMap<String, Student>();
#RequestMapping(method = RequestMethod.GET)
public String sayHello(ModelMap model) {
model.addAttribute("greeting", "Hello World from Spring 4 MVC");
return "welcome";
}
#RequestMapping(value = "/helloagain", method = RequestMethod.GET)
public String sayHelloAgain(ModelMap model) {
model.addAttribute("greeting", "Hello World Again, from Spring 4 MVC");
return "welcome";
}
/***
* #ModelAttribute = binds a method parameter or a method return value to a named model attribute and then exposes it to a web view.
* #param student
* #param result
* #param modelMap
* #return
* That is, #ModelAttribute methods are invoked before the controller methods annotated with #RequestMapping are invoked.
* The logic behind the sequence is that, the model object has to be created before any processing starts inside the controller methods.
*/
#RequestMapping(value="/", method = RequestMethod.POST)
public String addStudent(#ModelAttribute("addStudent") Student student, BindingResult result, ModelMap modelMap){
if(result.hasErrors()){
return "error";
}
else {
studentService.addStudent(student);
}
/*modelMap.addAttribute("nume", student.getNume());
modelMap.addAttribute("prenume", student.getPrenume());
persoaneAdaugate.put(student.getNume(), student);
System.out.println("Persoane adaugate: " + persoaneAdaugate +"\n");
System.out.println("nume: " + student.getNume()+" si prenume: " +student.getPrenume());
*/
return "success";
}
}
StudentDao
import com.websystique.springmvc.model.Student;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
public interface StudentDao {
List<Student> getAllStudents();
void addStudent(Student student);
}
StudentDaoImpl
import com.websystique.springmvc.model.Student;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Repository("studentDao")
#Service
#Transactional
public class StudentDaoImpl implements StudentDao{
#Autowired
private SessionFactory sessionFactory;
public List<Student> getAllStudents() {
return null;
// return sessionFactory.getCurrentSession().createQuery("from Date").list();
}
public void addStudent(Student student) {
sessionFactory.getCurrentSession().saveOrUpdate(student);
}
}
Student
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
#Entity
#Table(name="DATE")
public class Student implements Serializable{
#Id
#NotEmpty
#Column(name="nume", unique=true, nullable=false )
private String nume;
#NotEmpty
#Column(name="prenume", nullable = false)
private String prenume;
protected Student(){
}
Student(String nume, String prenume){
this.prenume=prenume;
this.nume=nume;
}
public String getNume(){
return nume;
}
public void setNume(String nume){
this.nume=nume;
}
public String getPrenume(){
return prenume;
}
public void setPrenume(String prenume){
this.prenume=prenume;
}
#Override
public String toString(){
return "Numele adaugat: nume= " + nume +" si prenume= " +prenume;
}
}
StudentService
import com.websystique.springmvc.model.Student;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
public interface StudentService {
List<Student> getAllStudents();
void addStudent(Student student);
}
StudentServiceImpl
import com.websystique.springmvc.dao.StudentDao;
import com.websystique.springmvc.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
#Service
#Transactional
public class StudentServiceImpl implements StudentService {
#Autowired
private StudentDao studentDao;
#Transactional
public List<Student> getAllStudents() {
return studentDao.getAllStudents();
}
public void addStudent(Student student) {
studentDao.addStudent(student);
}
}

Resources