Use HATEOAS RepresentationModel in parent abstract class - spring-boot

I t tried use new lastes version of Spring Hateoas 1.0 in my Spring Project, in this project all entities classes inherit from an Abstract Class, but in the Hateoas documentation my Entities must be extend the RepresentationModel Class
https://docs.spring.io/spring-hateoas/docs/1.0.1.RELEASE/reference/html/#fundamentals.representation-models
I've problems to extend the RepresentationModel on my Entity parent Class , somebody can help me please.
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import org.springframework.hateoas.RepresentationModel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
#MappedSuperclass
#Getter #Setter #NoArgsConstructor
public abstract class Entity<T> extends RepresentationModel<T> implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private T id;
#Column
private Date createAt;
#Column
private Date updateAt;
}

I didn't use generic classes, but instead cast the whole object back to my concrete class in my controller.
Here is my super class
public class AbstractEntity extends RepresentationModel<AbstractEntity> implements Serializable {
}
Now my class extends the AbstractEntity:
public class User extends AbstractEntity {}
And in the controller we can have a method for adding the selfRef:
private User addSelfLink(User user) {
return (User) user.add(linkTo(methodOn(UserController.class).getById(user.getId())).withSelfRel());
}
All we have to do is cast the object bask to the final object we are using

Related

jpa repositofy findall() returns empty list

I'm practicing making web pages using spring boot.
I created an h2 DB and connected it, and I want to show the name properties of the members table as a list on my web page.
I created the findall() method, but only an empty list is returned. What's wrong with my code?
my web page
MemberRepository
package com.example.testproject.store.h2.repository;
import com.example.testproject.store.h2.domain.Members;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface MemberRepository extends JpaRepository<Members, Integer> {
}
MemberService
package com.example.testproject.store.h2.service;
import com.example.testproject.store.h2.domain.Members;
import java.util.List;
public interface MemberService {
List<Members> getAll();
}
MemberServiceImpl
package com.example.testproject.store.h2.service;
import com.example.testproject.store.h2.domain.Members;
import com.example.testproject.store.h2.repository.MemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.lang.reflect.Member;
import java.util.List;
#Service(value = "memberServiceImpl")
public class MemberServiceImpl implements MemberService {
#Autowired
private MemberRepository memberRepository;
public List<Members> getAll(){
return memberRepository.findAll();
}
}
MemberController
package com.example.testproject.controller;
import com.example.testproject.store.h2.domain.Members;
import com.example.testproject.store.h2.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
#RestController
public class MemberController {
#Autowired
private MemberService memberService;
#GetMapping(value = "/members")
public List<Members> getAll() {
List<Members> users = memberService.getAll();
return users;
}
/*#GetMapping(value = "/members")
public List<Members> getAll() throws Exception {
return memberService.getAll();
}*/
}
Members(Entity)
package com.example.testproject.store.h2.domain;
import jakarta.persistence.*;
#Entity
#Table(name = "members")
public class Members {
#Id
private int id;
#Column
private String name;
}
I want to show the name properties of the members table as a list on my web page.
You have missed the getter setter method in entity class either you need to 1:-define getter setter method for each field or
2:-you need to add lombook dependency in pom.xml file and add #Data annootation on top of entity class so that when spring uses your entity can set and get the value from database and if you dontot want to give id explicitly then add #GeneratedValue(strategy=GenerationType.AUTO) so that spring automatically increase you id
I think you missed getters and setters in your Entity
Class just add them by using #Data annotation and try again.
You missed getters and setters for the fields in your Entity
You do not need any library, you can write it by yourself.
Otherwise, even if you use lombok, you should avoid to use #Data annotation on Entity, because it could lead to errors with default implementation of equals and hashCode. Instead you can use annotations #Getter and #Setter on the class.

Data is not getting fetched from MySQL Database while creating an application from Spring Boot

I recently began working on creating a REST API using Spring Boot. While running the code, though I don't get any error, I get a blank screen when using localhost:8080/expenses/ and I'm not sure why.
My Entity Class
import javax.persistence.*;
import java.math.BigDecimal;
import java.sql.Date;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#Table(name = "tbl_expenses")
public class Expense {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name ="expense_name")
private String name;
private String description;
#Column(name ="expense_amount")
private BigDecimal amount;
private String category;
private Date date;
}
My Expense Controller
package in.pranay.expensetrackerapi.controller;
import in.pranay.expensetrackerapi.entity.Expense;
import in.pranay.expensetrackerapi.service.ExpenseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class ExpenseController {
#Autowired
private ExpenseService expenseService;
#GetMapping("/expenses")
public List<Expense> getAllExpenses() {
return expenseService.getAllExpenses();
}
}
My Repository
package in.pranay.expensetrackerapi.repository;
import in.pranay.expensetrackerapi.entity.Expense;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface ExpenseRepository extends JpaRepository<Expense, Long> {
}
My Application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/expensetracker
spring.datasource.username=root
spring.datasource.password=pranay#1404
Can anyone please help me solve the issue?

Validate input inside embedded lists using #DecimalMin and #Valid

So what I am trying to do is to create embedded classes with validation in each class and then get the desired error message when I enter an illegal value. When I have embedded classes, validation suddenly stops working for some reason. I have extracted the core of the problem in the classes below
UserController Class:
// UserController.java
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
#RestController
public class UserController {
public void printUsers(#Valid List<User> users) {
System.out.println(users.get(0).getPeople().get(0).getAge());
}
#GetMapping("/")
public void getUser() {
List<User> users = new ArrayList<>();
Person person = new Person();
person.setAge(-10.0);
person.setFirstName("Test");
person.setLastName("Embedded Validation");
List<Person> persons = new ArrayList<>();
persons.add(person);
User user = new User(persons);
users.add(user);
printUsers(users);
}
}
User Class:
// User.java
package com.example.demo;
import lombok.Builder;
import lombok.Data;
import javax.validation.constraints.NotNull;
import java.util.List;
#Data
#Builder
public class User {
#NotNull
private List<Person> people;
}
Person Class:
// Person.java
package com.example.demo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.NotNull;
#Data
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class Person {
#NotNull
#DecimalMin("0.0")
private double age;
#NotNull
private String firstName;
#NotNull
private String lastName;
}
If you run this it will print -10.0, but I have explicitly told the Person class to have a min DecimalVal of 0.0, so my assignment of person.setAge(-10.0); in the UserController class should not be allowed.
How come validation on embedded classes do not work?

No qualifying bean of type,expected at least 1 bean which qualifies as autowire, org.springframework.beans.factory.UnsatisfiedDependencyException:

I Created a simple Springboot Application with H2 DB. Not able to start the spring boot Application getting below error on startup. I have added all the necessary configurations.
Exception encountered during context initialization - cancelling
refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'studentController': Unsatisfied
dependency expressed through field 'studentService'; nested exception
is org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.example.test.serviceimpl.StudentServiceImpl' available: expected
at least 1 bean which qualifies as autowire candidate. Dependency
annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Controller:
package com.example.test.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.example.test.serviceimpl.StudentServiceImpl;
import comm.example.test.model.Student;
#RestController
public class StudentController {
#Autowired(required=true)
private StudentServiceImpl studentService;
#GetMapping("/student")
private List<Student> getAllStudent() {
return studentService.getAllStudent();
}
#GetMapping("/student/{id}")
private Student getStudent(#PathVariable("id") Long id) {
return studentService.getStudentById(id);
}
}
Student Pojo class
package comm.example.test.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
#Getter
#Setter
#AllArgsConstructor
#Entity
#Table(name="student")
public class Student {
#Id
#Column
private Long id;
#Column
private String name;
#Column
private int age;
#Column
private String email;
}
StudentService Interface:
package com.example.test.service;
import java.util.List;
import comm.example.test.model.Student;
public interface StudentService {
List<Student> getAllStudent();
Student getStudentById(Long id);
}
StudentServiceImpl:
package com.example.test.serviceimpl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.example.test.repository.serviceimpl.StudentRepositoryServiceImpl;
import com.example.test.service.StudentService;
import comm.example.test.model.Student;
public class StudentServiceImpl implements StudentService {
#Autowired
private StudentRepositoryServiceImpl serviceImpl;
#Override
public List<Student> getAllStudent() {
return serviceImpl.getAllStudent();
}
#Override
public Student getStudentById(Long id) {
return serviceImpl.getStudentById(id);
}
}
RepositoryService:
package com.example.test.repository.serviceimpl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.test.repository.StudentRepository;
import comm.example.test.model.Student;
#Service
public class StudentRepositoryServiceImpl {
#Autowired
private StudentRepository repo;
public List<Student> getAllStudent() {
List<Student> students = new ArrayList<Student>();
repo.findAll().forEach(student -> students.add(student));
return students;
}
public Student getStudentById(Long id) {
return repo.findById(id).get();
}
}
Repository:
package com.example.test.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import comm.example.test.model.Student;
#Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}
Your StudentServiceImpl needs a #Service annotation to be injected.

APPLICATION FAILED TO START error encountered on SpringBoot

I'm self-studying in Spring boot application and encountered this problem. Weird thing is that I only followed the tutorial but still encountered this
Parameter 0 of constructor in com.example.Project1.service.PersonService required a bean of type 'com.example.Project1.dao.PersonDao' that could not be found.
I have one controller, 2 DAO files, 1 Person for model and 1 for service class.
These are my codes:
PersonController:
package com.example.Project1.api;
import com.example.Project1.model.Person;
import com.example.Project1.service.PersonService;
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;
#RequestMapping("api/v1/person")
#RestController
public class PersonController {
private final PersonService personService;
#Autowired
public PersonController(PersonService personService){
this.personService = personService;
}
#PostMapping
public void addPerson(#RequestBody Person person){
personService.addPerson(person);
}
}
FakePersonDataAccessService
package com.example.Project1.dao;
import com.example.Project1.model.Person;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
#Repository("fakeDao")
public class FakePersonDataAccessService implements PersonDao {
private static List<Person> DB = new ArrayList<>();
#Override
public int insertPerson(UUID id, Person person){
DB.add(new Person(id, person.getName()));
return 1;
}
}
PersonDao
package com.example.Project1.dao;
import com.example.Project1.model.Person;
import java.util.UUID;
public interface PersonDao {
int insertPerson(UUID id, Person person);
default int insertPerson(Person person){
UUID id = UUID.randomUUID();
return insertPerson(id, person);
}
}
Person
package com.example.Project1.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.UUID;
public class Person {
private final UUID id;
private final String name;
public Person(#JsonProperty("id") UUID id, #JsonProperty("name") String name){
this.id = id;
this.name = name;
}
public UUID getId(){
return id;
}
public String getName(){
return name;
}
}
PersonService
package com.example.Project1.service;
import com.example.Project1.dao.PersonDao;
import com.example.Project1.model.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
#Service
public class PersonService {
private final PersonDao personDao;
#Autowired
public PersonService(#Qualifier("mongo") PersonDao personDao){
this.personDao = personDao;
}
public int addPerson(Person person){
return personDao.insertPerson(person);
}
}
I've tried googling the error but found no answer. Hope someone can enlighten me about the error encountered. Thank you~!
You only have "fakeDao" qualifier class that implements PersonDao but your injecting "mongo" qualifier. As another option, you can just removed the #Qualifier annotation in PersonService constructor since you only have one class that implements PersonDao

Resources