Can't get products by userId from repository - spring

I have 2 tables. One of them called 'products'
#Data
#Entity
#Table(name = "products")
#NoArgsConstructor
public class Product {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(length = 100)
#NotBlank(message = "Name must be written")
private String name;
#Column(length = 200)
#NotBlank(message = "Provide image (link in this case) of your product")
private String image;
#PositiveOrZero
private int amount;
#Column(length = 250)
#NotBlank(message = "description must be written")
#Size(min = 10, max = 250, message = "description is too long or empty")
private String description;
#PositiveOrZero
private float price;
#ManyToOne
#JoinColumn(name = "type_id")
private ProductType productType;
public Product(#NotBlank String name, String image, int amount, #NotBlank String description,
#PositiveOrZero float price, ProductType productType) {
this.name = name;
this.image = image;
this.amount = amount;
this.description = description;
this.price = price;
this.productType = productType;
}
}
another table is 'users'
#Data
#Entity
#NoArgsConstructor
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(length = 50)
#Size(min = 2, max = 30, message = "enter appropriate amount of letters, min 2")
private String username;
#Column(length = 100)
#Email(message = "Enter a valid email")
#NotBlank(message = "email should have a value")
private String email;
#Column(length = 50)
#NotBlank(message = "password should have a value")
#Size(min = 6, message = "password should at least consist of 6 characters")
private String password;
private boolean enabled;
private String role;
public User(#Size(min = 2, max = 30, message = "enter appropriate amount of letters, min 2")
String username,
#Email(message = "Enter a valid email")
#NotBlank(message = "email should have a value") String email,
#NotBlank(message = "password should have a value")
#Size(min = 6, message = "password should at least consist of 6 characters")
String password, boolean enabled, String role) {
this.username = username;
this.email = email;
this.password = password;
this.enabled = enabled;
this.role = role;
}
}
and also table that include both 'product_user' (many to many relationship)
it looks like this
#Data
#Entity
#Table(name = "product_user")
#AllArgsConstructor
#NoArgsConstructor
public class ProdAndUser{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Integer id;
#ManyToOne
#JoinColumn(name = "product_id")
Product product;
#ManyToOne
#JoinColumn(name = "user_id")
User user;
public ProdAndUser(Product product, User user) {
this.product = product;
this.user = user;
}
}
then I tried to get them from prodAndUser repository by UserId or by User as obj:
#Repository
public interface ProdAndUserRepository extends JpaRepository<ProdAndUser, Integer> {
List<ProdAndUser> getProdAndUsersByUserId(Integer id);
List<ProdAndUser> getAllByUser(User user);
}
my controller looks like this:
#ResponseBody
#GetMapping("/findByUsr/{user}")
public List<ProdAndUser> getByUser(#PathVariable User user){
return prodAndUserRepository.getAllByUser(user);
}
error:
{
"timestamp": "2022-02-12T05:52:53.165+00:00",
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/Cart/findByUsr"
}
I have tried to find them all by .findAll() and it worked fine. Also another tables work fine on their own

Look at the error it says (404) means something is not right with the path.
The path on the error does not contain user_id.

Related

Sending file and JSON in a many-to-many relationship

I have a model called EPI that has a many to many relationship with Model Images, I am not able to do the #PostMapping for this object.
see my code
EPI Entity:
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Table(name = "EPI")
public class EPI implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "Id_EPI")
private UUID id;
#Column(name = "Nome", nullable = false, length = 100)
private String nome;
#Column(name = "Marca", nullable = false, length = 100)
private String marca;
#Column(name = "CA", nullable = false, length = 100)
private String ca;
#Column(name = "Descricao", nullable = false)
private String descricao;
#Column(name = "Foto")
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "epi_images",
joinColumns = {
#JoinColumn(name = "epi_id")
},
inverseJoinColumns = {
#JoinColumn(name = "image_id")
})
private Set<ImageModel> foto;
#Column(name = "Quantidade", nullable = false)
private Integer quantidade;
}
Image Entity:
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#Builder
#Table(name = "image_model")
public class ImageModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
private String name;
#Column(name = "type")
private String type;
#Column(name = "image_data", unique = false, nullable = false, length = 100000)
private byte[] imageData;
}
Controller EPI:
#PostMapping("/addNewEPI")
public ResponseEntity<Object> salvarFEPI(#RequestPart("image")MultipartFile file,
#RequestPart("epiModel") EPI epi) throws IOException {
try {
ImageModel foto = productImageService.uploadImage(file);
epi.setFoto((Set<ImageModel>) foto);
return ResponseEntity.status(HttpStatus.CREATED).body(epiService.save(epi));
} catch (Exception e){
System.out.println(e.getMessage());
return null;
}
Service Image:
public ImageModel uploadImage(MultipartFile file) throws IOException {
ImageModel image = new ImageModel();
image.setName(file.getOriginalFilename());
image.setType(file.getContentType());
image.setImageData(ImageUtility.compressImage(file.getBytes()));
return image;
}
As I am passing the parameters in Postman:
enter image description here
Return from Spring Boot:
enter image description here
If anyone can help me I would be very grateful!
I tried passing the parameters in different ways. I just want it to populate my tables passing the parameters of the EPI entity and the Image file.
enter image description here

Spring boot table to show list of pets by owner id

I'm making a small school project Spring Boot web application. Right now I have made CRUD for Owners table in the database, what I'm trying to do next is when I click button "pets" I want to be able to show only those pets that has the same "owner_id". I guess I should receive "owner_id" from the button that was pressed. How can I make that it works the way it should work? Now when I press button "pets" it shows all list of the pets.
Owner class:
#Entity
#Table(name = "owners")
public class Owner {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "first_name", nullable = false)
private String firstName;
#Column(name = "last_name", nullable = false)
private String lastName;
#Column(name = "email", nullable = false)
private String email;
#OneToMany(targetEntity = Pet.class,cascade = CascadeType.ALL)
#JoinColumn(name = "owner_id", referencedColumnName = "id")
private List<Pet> pets;
public Owner() {
}
public Owner(String firstName, String lastName, String email) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
}
Pet class:
#Table(name = "pets")
public class Pet {
#Id
private Long id;
private String name;
private String breed;
private int age;
private double weight;
public Pet() {
}
public Pet(String name, String breed, int age, double weight) {
super();
this.name = name;
this.breed = breed;
this.age = age;
this.weight = weight;
}
}
Controller method for list of pets:
#GetMapping("/owner_pets")
public String getAllPetsByOwnerId(Model model) {
model.addAttribute("pets", petService.getAllPetsByOwnerId());
return "owner_pets";
}
Here is the code written so far but it only shows list of all pets
I saw your service method for PerService. I do not see any ownerId being passed to findByOwnerId method. That might be the reason why you are getting all pets in response. What you should ideally do is
package com.veterinary.Veterinary_system.service;
import java.util.List;
import com.veterinary.Veterinary_system.entity.Pet;
public interface PetService {
//Repository declaration
List < Pet > findByOwnerId(Long ownerId){
return petRepository.findByOwnerId(ownerId);
}
Pet savePet(Pet pet);
}

How to insert an object inside another in Spring

I'm trying to insert the Insurance object into **User **through an endpoint in Spring, but either the request asks me for all User attributes or the object is not inserted.
**User Class **
#Entity
#Table(name = "users",
uniqueConstraints = {
#UniqueConstraint(columnNames = "username"),
#UniqueConstraint(columnNames = "email")
})
#AllArgsConstructor
#NoArgsConstructor
#Data
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotBlank
#Size(max = 20)
private String username;
private String documento;
private String telefone;
#Value("${some.key:false}")
private boolean first_acess;
private String formacao;
private String sexo;
private String data_nascimento;
#NotBlank
#Size(max = 50)
#Email
private String email;
#NotBlank
#Size(max = 120)
private String password;
#ManyToMany(fetch = FetchType.LAZY)
#JoinTable( name = "user_roles",
joinColumns = #JoinColumn(name = "user_id"),
inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
#Embedded
private Address address;
#ManyToOne
#JoinColumn(name = "insuranceId")
private Insurance insurance;
Insurance class
#Data
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Table(name = "insurance")
public class Insurance {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long insuranceId;
private String name;
private String valor;
private String maximoDependentes;
private String vencimento;
private String descricao;
}
Request to insert into class
#PostMapping("/User/{id}/addPlan")
public ResponseEntity<User> addPlanToUser(#PathVariable("id") long id, #RequestBody SignInsuranceRequest signInsuranceRequest) {
User user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Not found User with id = " + id));
return new ResponseEntity<>(userRepository.save(user), HttpStatus.OK);
}
Custom request for the solution
public class SignInsuranceRequest {
#ManyToOne
#JoinColumn(name = "insuranceId", insertable = false, updatable = false)
private Insurance insurance;
public Insurance getInsurance() {
return insurance;
}
public void setInsurance(Insurance insurance) {
this.insurance = insurance;
}
}
I already tried to put the User in #RequestBody and just ask for the insurance and it didn't work either
Example of how it was done
#PutMapping("/User/{id}/addPlan")
public ResponseEntity<User> addPlanToUser(#PathVariable("id") long id, #RequestBody User user) {
User _user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Not found User with id = " + id));
_user.setInsurance(user.getInsurance());
return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
}
In this attempt, I would pass the id of an insurance in the body of the request and the ID of the user in the Header but the id of the database was not retrieved.
Response
{
"id": 1,
"username": "user",
"documento": null,
"telefone": null,
"first_acess": false,
"formacao": null,
"sexo": null,
"data_nascimento": null,
"email": "user#user.com",
"password": "$2a$10$DUkVRxFFiR7L2OpwwpxHyOCC.7v/iFLqp66BBqy3AC0lHrVa9lnQK",
"roles": [],
"address": null,
"insurance": {
"insuranceId": 1,
"name": "string",
"valor": "string",
"maximoDependentes": "string",
"vencimento": "string",
"descricao": "string"
}
}
I expected to insert an User class into a Insurance Class(Already created) and return the object of User completed.

Junit how to achieve100% coverage for Model class

I have a model class:
#Builder
#Data
#Entity
#AllArgsConstructor
#NoArgsConstructor
public class Employee {
#GeneratedValue(strategy = GenerationType.AUTO)
#Type(type="uuid-char")
#Column(updatable = false, nullable = false, unique = true)
#Id
private UUID id;
#Column(updatable = true, nullable = false, unique = true)
#Email(message = "Enter a valid email")
private String email;
#NotNull(message = "First name cannot be empty")
#Size(min = 3, message = "First name character must be more than 3!")
private String firstName;
#Size(min = 3, message = "Last name character must be more than 3!")
private String lastName;
#Range(min = 21, max = 55, message = "Age must be between 21 and 55")
private int age;
#JsonIgnore
private Double accBalance;
#NotNull(message = "Gender cannot be empty")
private String gender;
#NotNull(message = "Country cannot be empty")
private String country;
#JsonProperty("Job Scope")
private String designation;
#CreationTimestamp
private Date createdAt;
#DateTimeFormat
private Date birthDate;
}
And this is my test class:
class EmployeeTest {
#Test
public void testObjectMethod() {
Employee object = new Employee();
object.equals(new Employee());
object.hashCode();
object.toString();
}
#Test
public void testAll() {
Employee object = new Employee();
object.equals(Employee.builder().build());
}
}
And this is my coverage. Basically it only covers 73.8%. What other tests do I need to do to achieve 100%? As this covers quite a lot and doesn't need much of thinking, I would like to target 100%. Appreciate any help or pointers.
coverage
You need to do following
write test for equals
write test for hashcode
write test case for constructor no-arg and all arg
test case for setter and getter for all attribute
you can write assertNotNull for hashCode various tests.

Can't assign a default user_role="ROLE_USER" with Hibernate

I have a user model and I am triyng to set a default role="role_user" in my postgreSQL database when a user register. My User model is:
#Entity
#Table(name = "users")
public class User {
#NotEmpty(message = "Campul nu poate fi lasat gol")
#Size(min = 4, max = 16,message = "Dimensiunea trebuie sa fie intre 4 si 16 caractere")
private String firstName;
#NotEmpty(message = "Campul nu poate fi lasat gol")
#Size(min = 4, max = 16,message = "Dimensiunea trebuie sa fie intre 4 si 16 caractere")
private String lastName;
#Id
#NotEmpty(message = "Campul nu poate fi gol")
#Email(message = "Email-ul trebuie sa fie valid")
private String email;
#NotEmpty(message = "Campul nu poate fi gol")
#Size(min = 4, max = 60, message = "Parola trebuie sa contina minim 4 caractere")
private String password;
private String role;
private boolean enabled = true;
public User() {};
public User(String firstName, String lastName, String email, String password,String role) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
this.role = role;
}
How can I solve the problem. I saw another posts on stackoverflow but I don't understand, I'm quite new in Spring
You can just initialize your field with the default value.
private String role = "role_user";
public User(String firstName, String lastName, String email, String password,String role) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
if(role != null) { this.role = role; }; // if you need to keep the default value
}

Resources