Spring: validating #Entity fields with #Valid annotation in controller post request method - java

I have following problem. This is my entity:
package application.model;
import lombok.Data;
import javax.persistence.*;
import javax.validation.Valid;
import javax.validation.constraints.*;
import java.util.List;
#NamedQueries({
#NamedQuery(name = User.GET_USERS, query = User.QUERY_GET_USERS),
#NamedQuery(name = User.VERIFY_CREDENTIALS, query = User.QUERY_VERIFY_CREDENTIALS),
#NamedQuery(name = User.GET_USER_ROLE, query = User.QUERY_GET_USER_ROLE),
#NamedQuery(name = User.GET_USER_ID_BY_EMAIL, query = User.QUERY_GET_USER_ID_BY_EMAIL)
})
#Data
#Entity
#Table(name = "users")
public class User {
public static final String GET_USERS = "User.get_users";
public static final String QUERY_GET_USERS = "select u from User u";
public static final String VERIFY_CREDENTIALS = "User.verify_credentials";
public static final String QUERY_VERIFY_CREDENTIALS = "select u from User u where u.email = :email and u.password = :password";
public static final String GET_USER_ROLE = "User.get_role";
public static final String QUERY_GET_USER_ROLE = "select u.roles from User u where u.id= :id";
public static final String GET_USER_ID_BY_EMAIL = "User.get_userId_by_mail";
public static final String QUERY_GET_USER_ID_BY_EMAIL = "select u from User u where u.email= :email";
#Id
#NotNull
#GeneratedValue(strategy = GenerationType.SEQUENCE)
#Column(name = "id")
public int id;
#NotEmpty(message="provide firstname")
#Size(min=4,message = "minimum 4 chars")
#Column(name="firstname",nullable = false)
private String firstname;
#NotEmpty(message="provide lastname")
#Size(min=4,message = "minimum 4 chars")
#Column(name="lastname",nullable = false)
private String lastname;
#NotEmpty(message="provide mail")
#Email(message = "mail should be valid")
#Column(name="email",unique = true,nullable = false)
private String email;
#NotEmpty(message="provide pass")
#Size(min=4,message = "minimum 4 chars")
#Column(name="password",nullable = false)
private String password;
#ManyToMany
#JoinTable(name="user_roles")
private List<Role> roles;
}
dao layer:
package application.dao;
import application.model.Role;
import application.model.User;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
#Repository
public class UserDAOImpl implements UserDAO {
#PersistenceContext(type = PersistenceContextType.EXTENDED)
private EntityManager em;
#Transactional
#Override
public User addUser(User user) {
return em.merge(user);
}
#Override
public User addCustomerRole(User user) {
List<Role> roles= new ArrayList<>();
roles.add(em.find(Role.class,3));
user.setRoles(roles);
return user;
}
#Override
public User addSellerRole(User user) {
List<Role> roles= new ArrayList<>();
roles.add(em.find(Role.class,2));
user.setRoles(roles);
return user;
}
}
service layer:
package application.service;
import application.controller.CommonAPIController;
import application.dao.UserDAO;
import application.model.User;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import java.util.Collection;
import java.util.List;
#Service
public class UserServiceImpl implements UserService {
final static Logger LOGGER = Logger.getLogger(UserServiceImpl.class.getName());
private final UserDAO userDAO;
public UserServiceImpl(UserDAO userDAO) {
this.userDAO = userDAO;
}
#Override
public User addCustomer(User user) {
return userDAO.addCustomerRole(userDAO.addUser(user));
}
}
and controller:
package application.controller;
import application.model.User;
import application.service.UserService;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
#RestController
public class CustomerAPIController {
private final UserService userService;
public CustomerAPIController(UserService userService) {
this.userService = userService;
}
#PostMapping(value = "/customer/register")
public User addCustomer(#RequestBody #Valid User user){
return userService.addCustomer(user);
}
}
I want to validate field in my User entity, I add validation constraints to Entity and #Valid annotation in controller - next to #RequestBody.
I used this tutorial how to do it: https://mkyong.com/spring-boot/spring-rest-validation-example/
After build I still can send json to /customer/register with payload with empty fields:
{
"firstname": "",
"lastname": "",
"email": "",
"password": "pass"
}
User is successfully registered, although annotations in User entity should not allow to do this?
Do you see what i'm doing wrong?
My project is Spring, in tutorial we have SpringBoot, there's a difference?
Also i have a dao and service layer between entity and controller and i using lombok's #Data annotation.
These details make a difference here or is the error elsewhere?

try to add BindingResults like this
#PostMapping(value = "/customer/register")
public User addCustomer(#RequestBody #valid BindingResults result,User user){
if(results.hasErrors()){
return some error page;
}
else{
return userService.addCustomer(user);
}

Ensure that your controller class is annotated with #Validated

Related

Could not resolve property error when debugging application

Im totally new to springboot and it get these errors when i try debugging them. They include;
could not resolve property: orderID of: com.DigitalVision.service.models.DeliveryStatus
could not resolve property: orderID of: com.DigitalVision.service.models.DeliveryStatus [Select s from com.DigitalVision.service.models.DeliveryStatus s where s.orderID = ?1]
Among a few of them, some included that there was an error creating bean with name deliveryStatusRepository.
Courier controller class
package com.DigitalVision.service.controllers;
import com.DigitalVision.service.models.Courier;
import com.DigitalVision.service.services.CourierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
#RestController
#RequestMapping("/courier")
#Service
public class CourierController
{
private CourierService courierService;
#Autowired
public CourierController(CourierService courierService) {
this.courierService = courierService;
}
#CrossOrigin
#RequestMapping(path = "/update-status/{status}/order-id/{orderId}",
method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity getAttendanceByDateRange(#PathVariable("status") String status,
#PathVariable("orderId") Long orderId) throws Exception {
Courier courier = courierService.updatestatus(status,orderId);
if (courier == null ) {
return new ResponseEntity(HttpStatus.NO_CONTENT);
}
return new ResponseEntity(courier, HttpStatus.ACCEPTED);
}
}
I have not done a controller class for the delivery status one yet
Courier class
#Entity
#Table
public class Courier implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long CourierID;
public Long OrderID;
public String Status;
Delivery status
#Entity
#Table
public class DeliveryStatus implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long DeliveryStatusID;
public Long OrderID;
public String Status;
public LocalDate Date;
Order class
public class Order implements Serializable {
public Long OrderID;
public Long CustomerID;
public Long ProductID;
public String Quantity;
Deliverystatusrepository
import com.DigitalVision.service.models.DeliveryStatus;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
#Repository
public interface DeliveryStatusRepository extends JpaRepository<DeliveryStatus, Long> {
#Query("Select s from DeliveryStatus s where s.orderID = ?1")
DeliveryStatus findDeliveryStatusIDByOrderID(Long id);
}
Courier service
public Courier updatestatus(String Status, Long courierID){
Courier courier = courierRepository.getReferenceById(courierID);
courier.setStatus(Status);
Courier courierSave = courierRepository.save(courier);
if(courierSave == null ){
return null;
}
deliveryStatusService.updatestatus(courierSave);
return courierSave;
}
Delivery status service
public DeliveryStatus updatestatus (Courier courier ){
DeliveryStatus deliveryStatus = deliveryStatusRepository.findDeliveryStatusIDByOrderID(courier.OrderID);
deliveryStatus.setStatus(courier.Status);
return deliveryStatusRepository.save(deliveryStatus);
}
The purpose of this code is to automatically change the status in the deliverystatus table when the courier status column is updated.
If anyone can help me find the error it would be greatly appreciated

User is in database, but it still lets him register unlimited amount of times

While there is user in the database, another user with exactly the same credentials is "successfully" inserted in the database...
Hello! I'm building my own ecommerce app and I included spring security. Now, while I was developing security part of the app, I tried it to see if it's working and once I entered desired info in the request body, for the first request the user was successfully inserted in the database, but when I tried to do it the second time, to check if the userExists which throws and error that user is already registered, works, it just added another user with the same credentials (name, lastname, mail and so). I go to userRepository to check if there is already the user with the same email, it makes sense what i wrote, but it doesnt work...Please help...Here are all the files:
EDIT : Mistakenly copied UserRegistrationController twice...So here is the userService.java:
package com.marin.thrift.service;
import com.marin.thrift.dao.UserRepository;
import com.marin.thrift.entity.User;
import lombok.AllArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
#Service
#AllArgsConstructor
public class UserService implements UserDetailsService {
private final UserRepository userRepository;
private final static String USER_NOT_FOUND = "user with email %s not found";
private final BCryptPasswordEncoder bCryptPasswordEncoder;
#Override
public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
return userRepository.findByUsername(email).orElseThrow(()-> new UsernameNotFoundException(String.format(USER_NOT_FOUND, email)));
}
public String singUpUser(User user){
boolean userExists = userRepository.findByUsername(user.getEmail()).isPresent();
if(userExists){
return "user already in place";
}
String encodedPassword = bCryptPasswordEncoder.encode(user.getPassword());
user.setPassword(encodedPassword);
userRepository.save(user);
return "it works";
}
}
package com.marin.thrift.registration;
import lombok.AllArgsConstructor;
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;
#RestController
#RequestMapping(path = "api/v1/registration")
#AllArgsConstructor
public class UserRegistrationController {
private RegistrationService registrationService;
#PostMapping
public String register(#RequestBody registrationRequest request){
return registrationService.register(request);
}
}
package com.marin.thrift.registration;
import lombok.AllArgsConstructor;
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;
#RestController
#RequestMapping(path = "api/v1/registration")
#AllArgsConstructor
public class UserRegistrationController {
private RegistrationService registrationService;
#PostMapping
public String register(#RequestBody registrationRequest request){
return registrationService.register(request);
}
}
package com.marin.thrift.registration;
import com.marin.thrift.entity.Role;
import com.marin.thrift.entity.User;
import com.marin.thrift.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
#Service
#AllArgsConstructor
public class RegistrationService {
private final EmailValidator emailValidator;
private final UserService userService;
public String register(registrationRequest request) {
Boolean isValidEmail = emailValidator.test(request.getEmail());
if (!isValidEmail){
throw new IllegalStateException("Email is not valid");
}
return userService.singUpUser(new User(request.getFirstName(), request.getLastName(),
request.getPassword(), request.getEmail(), Role.USER));
}
}
package com.marin.thrift.entity;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import javax.persistence.*;
import java.util.Collection;
import java.util.Date;
#Entity
#Data
#Table(name = "users")
public class User implements UserDetails {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "date_of_birth")
private Date dateOfBirth;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
private Role role;
private Boolean locked = false;
private Boolean enabled = false;
public User(String firstName, String lastName, String password, String email, Role role) {
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.email = email;
this.role = role;
}
public User() {
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.name());
return null;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername(){
return email;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return !locked;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return enabled;
}
}
package com.marin.thrift.security.config;
import com.marin.thrift.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
#Configuration
#AllArgsConstructor
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
private final UserService userService;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
#Override
protected void configure(HttpSecurity http) throws Exception{
http.csrf()
.disable().authorizeRequests()
.antMatchers("/api/v*/registration/**").permitAll()
.anyRequest().authenticated().and().formLogin();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
auth.authenticationProvider(daoAuthenticationProvider());
}
#Bean
public DaoAuthenticationProvider daoAuthenticationProvider(){
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(bCryptPasswordEncoder);
provider.setUserDetailsService(userService);
return provider;
}
}
package com.marin.thrift.registration;
import lombok.*;
#Getter
#AllArgsConstructor
#EqualsAndHashCode
#ToString
public class registrationRequest {
private final String firstName;
private final String lastName;
private final String password;
private final String email;
}
Without UserService it's hard to say what is happen. But if I see your jpa mapping I can guess that if you want unique entry per unique user, you have to delete generated column id. And instead you have to put #Id annotation on email. In this case you need also make changes in sql table.
Or as alternative you can stay by current mapping and simply conduct findByEmail before save entity. And if Optional is not empty - then user is already in database registred.
I just fixed my mistake. The mistake was in the database where I forgot to set email as unique. Once I did that, the code works perfectly.

Receiving an "Unsatisfied dependency expressed through field 'userService'; nested exception"

Not sure what is happening here. The error is
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'authenticationController': Unsatisfied dependency expressed through field 'userService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userService' - Unsatisfied dependency expressed through constructor parameter 1"
Am I missing something here?
My controller -
import com.***.model.User;
import com.***.service.AuthTokenService;
import com.***.service.Authentication;
import com.***.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
#Controller
#RestController
#RequestMapping("/api/v1")
public class AuthenticationController {
#Autowired
UserService userService;
AuthTokenService authTokenService;
#GetMapping(path = "/users")
public ResponseEntity<?> listUser() {
List<User> resource = userService.getUser();
return ResponseEntity.ok(resource);
}
#PostMapping(path = "/register")
public ResponseEntity<?> register(#RequestBody User newUser) {
User user = userService.findUserByEmail(newUser.getEmail());
User unconfirmedUser = userService.registerUser(newUser);
return ResponseEntity.ok(unconfirmedUser);
}
My UserService -
import com.***.model.User;
import com.***.repository.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
#Component
#AllArgsConstructor
public class UserService {
#Autowired
UserRepository userRepository;
AuthTokenService authTokenService;
EmailSenderService emailSenderService;
void sendAuthenticationEmail(String userMail, String token) {
final SimpleMailMessage mailMessage = new SimpleMailMessage();
mailMessage.setTo(userMail);
mailMessage.setSubject("Mail Confirmation Link!");
mailMessage.setFrom("<Mail Service>");
mailMessage.setText( "Thank you for joining ***! Please click below to activate your account." + "http://8080/api/v1/confirm?token=" + token);
emailSenderService.sendEmail(mailMessage);
}
public User registerUser(User user) {
final Authentication authenticationToken = new Authentication(user);
authTokenService.saveAuthenticationToken(authenticationToken);
sendAuthenticationEmail(user.getEmail(), authenticationToken.getUserToken());
return userRepository.save(user);
}
public void confirmUser(Authentication authenticationToken) {
final User user = authenticationToken.getUser();
user.setEnabled(true);
userRepository.save(user);
authTokenService.deleteAuthenticationToken((long) authenticationToken.getId());
}
}
Authentication -
import com.***.model.User;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.*;
import java.time.LocalDate;
import java.util.UUID;
#Entity
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor
public class Authentication {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String userToken;
private LocalDate dateTimeCreated;
#OneToOne(targetEntity = User.class, fetch = FetchType.EAGER)
#JoinColumn(nullable = false, name = "id")
private User user;
Authentication(User user) {
this.user = user;
this.dateTimeCreated = LocalDate.now();
this.userToken = UUID.randomUUID().toString();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserToken() {
return userToken;
}
public void setUserToken(String userToken) {
this.userToken = userToken;
}
public LocalDate getDateTimeCreated() {
return dateTimeCreated;
}
public void setDateTimeCreated(LocalDate dateTimeCreated) {
this.dateTimeCreated = dateTimeCreated;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Authentication token repo -
package com.***.repository;
import com.***.service.Authentication;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
#Repository
public interface AuthenticationTokenRepository extends CrudRepository<Authentication, Long> {
Optional<Authentication> findAuthenticationToken(String token);
}
Picture of file structure HERE
Log of error
Based on your error it looks like you don't know how to create JpqRepository method signature based queries. You can read about it here : https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
I'm guessing that your method in AuthenticationTokenRepository called findAuthenticationToken(String someField) should be named findBySomeField(String someField). Also make sure you have getter for someField
Would be easier if you could provide your AuthenticationTokenRepository and Authenctication classes
Edit:
Change your method in AuthenticationTokenRepository to findByUserToken(String userToken)

How to add element to bidirectional relationship correctly? I am getting collection is evicted

I have the following classes
public class User {
#OneToMany(
fetch = FetchType.EAGER,
mappedBy = "user",
cascade = CascadeType.ALL
)
private Set<UserSession> sessions;
public UserSession login() {
UserSession session = new UserSession();
session.setUser(this);
session.persistAndFlush();
this.persistAndFlush();
return session;
}
....
public class UserSession {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "user_id")
protected User user;
as you see, I am adding session from it's side. Sometimes in other times I am getting
caused by: org.hibernate.HibernateException: collection was evicted
How to do correctly?
To add the element in Bi-Directional relationship,
create a helper method in parent class for adding or removing child entity.
create child entity and using helper method add it to parent's collection
save child entity
Sample code:
#Getter
#Setter
#Entity
class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<UserSession> userSessions = new HashSet<>();
public void addNewSession(UserSession userSession) {
this.userSessions.add(userSession);
userSession.setUser(this);
}
public void removeSession(UserSession userSession) {
this.userSessions.remove(userSession);
userSession.setUser(null);
}
}
Fully working code:
package com.example.demo;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.hibernate.annotations.ResultCheckStyle;
import org.hibernate.annotations.SQLDelete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.repository.CrudRepository;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
#RestController
#RequestMapping("/users")
#EnableTransactionManagement
public class UserAndSessionsController {
private final UserService userService;
#Autowired
public UserAndSessionsController(UserService userService) {
this.userService = userService;
}
#GetMapping
public Iterable<User> list() {
return userService.list();
}
#PostMapping
public User create(#RequestBody User user) {
return userService.save(user);
}
#GetMapping("/sessions")
public Iterable<UserSession> sessions(#RequestParam("userId") Integer userId) {
return userService.getUserSessions(userId);
}
#PostMapping(path = "login")
public UserSession login(#RequestBody User user) throws Throwable {
return userService.createNewLoginSession(user);
}
#PostMapping(path = "logout")
public UserSession logout(#RequestBody UserSessionsDto userSessionsDto) throws Throwable {
return userService.invalidateLoginSession(userSessionsDto.getUser(), userSessionsDto.getUserSession());
}
#Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
#ToString
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
class UserSessionsDto {
private User user;
private UserSession userSession;
}
#Getter
#Setter
#Entity
class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
#OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true)
private Set<UserSession> userSessions = new HashSet<>();
public void addNewSession(UserSession userSession) {
this.userSessions.add(userSession);
userSession.setUser(this);
}
public void removeSession(UserSession userSession) {
this.userSessions.remove(userSession);
userSession.setUser(null);
}
}
#Getter
#Setter
#Entity
#SQLDelete(sql = "update USER_SESSION set valid = false where id = ?", check = ResultCheckStyle.COUNT)
class UserSession {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String SessionId;
private boolean valid;
#JsonIgnore
#ManyToOne(fetch = FetchType.LAZY, optional = false)
private User user;
}
#Service
class UserService {
private final UserRepository userRepository;
private final UserSessionRepository userSessionRepository;
#Autowired
UserService(UserRepository userRepository, UserSessionRepository userSessionRepository) {
this.userRepository = userRepository;
this.userSessionRepository = userSessionRepository;
}
#Transactional
public User save(User user) {
return userRepository.save(user);
}
#Transactional(readOnly = true)
public Iterable<User> list() {
return userRepository.findAll();
}
#Transactional(readOnly = true)
public Iterable<UserSession> getUserSessions(Integer userId) {
// return userRepository.findById(userId)
// .map(User::getUserSessions)
// .orElse(Collections.emptySet());
return userSessionRepository.findUserSessionsByUser_Id(userId);
}
#Transactional
public UserSession createNewLoginSession(User user) throws Throwable {
final User dbUser = userRepository
.findById(user.getId())
.orElseThrow(() -> new RuntimeException("User : " + user.getName() + " not found"));
final UserSession userSession = new UserSession();
userSession.setSessionId(UUID.randomUUID().toString());
userSession.setValid(true);
dbUser.addNewSession(userSession);
userSessionRepository.save(userSession);
return userSession;
}
#Transactional
public UserSession invalidateLoginSession(User user, UserSession userSession) throws Throwable {
final User dbUser = userRepository
.findById(user.getId())
.orElseThrow(() -> new RuntimeException("User : " + user.getName() + " not found"));
final UserSession dbUserSession = userSessionRepository
.findById(userSession.getId())
.orElseThrow(() -> new RuntimeException("UserSession : " + userSession.getSessionId() + " not found"));
dbUser.removeSession(dbUserSession);
userSessionRepository.delete(dbUserSession);
return dbUserSession;
}
}
#Repository
interface UserRepository extends CrudRepository<User, Integer> {
}
#Repository
interface UserSessionRepository extends CrudRepository<UserSession, Integer> {
Iterable<UserSession> findUserSessionsByUser_Id(Integer userId);
}

GET request returns a {} but the db table has entries (Spring boot+JPA+MySQL)

I have tried to receive all the entries in a table as JSON objects, get request shows '200 OK' but it returns a [{}].
import javax.persistence.*;
import java.time.LocalDateTime;
#Entity
#Table(name = "man")
public class User {
#Id
#GeneratedValue
#Column(name = "man_id")
private Integer id;
#Column(name = "man_name")
private String name;
#Column(name = "salary")
private Double salary;
#Column(name = "reg")
private LocalDateTime dateTime;
}
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDAO extends JpaRepository<User,Integer> {
}
Service Layer
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class UserService {
private final UserDAO userDAO;
#Autowired
public UserService(UserDAO userDAO) {
this.userDAO = userDAO;
}
public List<User> findAll(){
return userDAO.findAll();
}
}
Controller
import org.springframework.beans.factory.annotation.Autowired;
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;
#RestController
#RequestMapping("/man")
public class UserControl {
private final UserService userService;
#Autowired
public UserControl(UserService userService) {
this.userService = userService;
}
#GetMapping("/all")
public List<User> findAll(){
return userService.findAll();
}
}
apllication.yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test
username: root
password: onionnetwork
jpa:
hibernate.dll-auto: update
generate: true
show-sql: true
Used Dependencies: starter-web , stater-jpa , mysql connector
NOTE: I'm currently learning spring boot through YouTube tutorials, so there will be some cringy programming practices.If you guys could help me with reviews and good resources to learn spring-boot, much appreciated. :)

Categories