I'm trying make a test to Update User method that first get a User by id and after update the user , work it, but when I try to make a test in the Junit show me that couldn't find the user by Id. Can anyone help me, please?
UserClass
package br.com.projectsmanagement.entities;
import java.util.Date;
import java.util.Objects;
import jakarta.persistence.*;
#Entity
#Table(name = "tb_users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
private String password;
#Temporal(TemporalType.TIMESTAMP)
private Date dataCadastro;
public User() {
}
public User(String name, String email, String password, Date dataCadastro) {
this.name = name;
this.email = email;
this.password = password;
this.dataCadastro = dataCadastro;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getDataCadastro() {
return dataCadastro;
}
public void setDataCadastro(Date dataCadastro) {
this.dataCadastro = dataCadastro;
}
#Override
public int hashCode() {
return Objects.hash(id);
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
return Objects.equals(id, other.id);
}
}
UserServiceImpl
#Override
public User updateUser(Long id, User user) {
try {
User userUpdated = userRepository.findById(id).get();
userUpdated.setName(user.getName());
userUpdated.setPassword(user.getPassword());
return userRepository.saveAndFlush(userUpdated);
} catch (NoSuchElementException e) {
throw new InvalidIdException("Usuário não encontrado!");
}
}
And finally my UserServiceImplTest
package br.com.projectsmanagement.services.impl;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.context.SpringBootTest;
import br.com.projectsmanagement.entities.User;
import br.com.projectsmanagement.exception.EmailExistException;
import br.com.projectsmanagement.repositories.UserRepository;
#SpringBootTest
class UserServiceImplTest {
#InjectMocks
private UserServiceImpl userServiceImpl;
#Mock
private UserRepository userRepository;
private User user;
private Optional<User> optionalUser;
#BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
startUser();
}
#Test
void whenFindAllThenReturnAnListofUsers() {
when(userRepository.findAll()).thenReturn(List.of(user));
List<User> response = userServiceImpl.listUsers();
assertNotNull(response);
assertEquals(1, response.size());
assertEquals(User.class, response.get(0).getClass());
}
#Test
void whenFindByIdThenReturnAnUserInstance() {
when(userRepository.findById(anyLong())).thenReturn(optionalUser);
Optional<User> response = userServiceImpl.getUserById(1L);
assertThat(response).isPresent();
assertEquals(optionalUser.getClass(), response.getClass());
assertEquals(optionalUser.get().getName(), "Valdir");
}
#Test
void whenRegisterThenReturnSuccess() {
when(userRepository.saveAndFlush(any())).thenReturn(user);
User response = userServiceImpl.registerUser(user);
assertNotNull(response);
assertEquals(User.class, response.getClass());
assertEquals(user.getId(), response.getId());
}
#Test
void whenRegisterThenReturnAnEmailExistException() {
when(userRepository.findByEmail(anyString())).thenReturn(user);
try {
userServiceImpl.registerUser(user);
} catch (ClassCastException e) {
assertEquals(EmailExistException.class, e.getClass());
assertEquals("Esse e-mail já está cadastrado!", e.getMessage());
}
User response = userServiceImpl.registerUser(user);
assertNotNull(response);
assertEquals(User.class, response.getClass());
assertEquals(user.getId(), response.getId());
}
#Test
void whenUpdateThenReturnSuccess() {
when(userRepository.saveAndFlush(any())).thenReturn(user);
User response = userServiceImpl.updateUser(1L, user);
assertNotNull(response);
assertEquals(User.class, response.getClass());
}
#Test
void testDeleteUser() {
fail("Not yet implemented");
}
private void startUser() {
user = new User("Valdir", "valdir#gmail.com", "123456", new Date());
optionalUser = Optional.of(new User("Valdir", "valdir#gmail.com", "123456", new Date()));
}
}
I modified my class many times, but even doesn't work it
I think in your test case whenUpdateThenReturnSuccess(), you forgot to mock the userRepository.findById(id) that you call when updating your user.
If not mocked, it returns null.
#Test
void whenUpdateThenReturnSuccess() {
when(userRepository.findById(anyLong())).thenReturn(optionalUser);
when(userRepository.saveAndFlush(any(User.class))).thenReturn(user);
User response = userServiceImpl.updateUser(1L, user);
assertNotNull(response);
assertEquals(User.class, response.getClass());
}
Related
I'm trying to set all the values of a column of my H2 bank to false at 1:00 PM, but I'm having difficulties doing that, the message is being printed on the console, but the votes remain as TRUE.
My table looks like this, I would like every day at 1:00PM the values of the VOTED field to be FALSE
ID
EMAIL
PASSWORD
NAME
VOTED
1
bruno#gmail.com
$2a$10$j1Eic8Okp.IczSVQbU.ru.s.dXoxd1fdzWtK2os9oE9y9ZO8wvMx6
Bruno
TRUE
2
james#gmail.com
$2a$10$F/KLm5ULaNRVEL/K6MMeveZXr770G5cI3S7HZnEw.b7TZDENkCWBC
James
TRUE
3
robert#gmail.com
$2a$10$uHZjSrroGBtRBB/V.norRuOcDVz42MXnm0/2yLPGpE3P5XtPRo7L6
Robert
FALSE
This is the logic I'm using in my UserServices.java
Despite the project running, users remain as TRUE after the time determined in #Scheduled
#Scheduled(cron = "0 00 13* * *")
public void resetVotes() throws InterruptedException {
List<User> userArray = repository.findAll();
for(User user: userArray ) {
user.setVoted(false);
}
}
And this is the message I get on the console when I arrive at the time I determined in #Scheduled
Hibernate:
select
user0_.id as id1_1_,
user0_.email as email2_1_,
user0_.password as password3_1_,
user0_.name as name4_1_,
user0_.voted as voted5_1_
from
db_users user0_
Here are the classes I'm using for the project:
User.java
package com.dbserver.restaurantes.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "db_users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "Name")
private String username;
private String email;
private String password;
private Boolean voted = false;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getVoted() {
return voted;
}
public void setVoted(Boolean voted) {
this.voted = voted;
}
}
UserDTO.java
package com.dbserver.restaurantes.dto;
import com.dbserver.restaurantes.entities.User;
public class UserDTO {
private Long id;
private String username;
private String email;
private String password;
private Boolean voted = false;
public UserDTO() {
}
public UserDTO(Long id, String username, String email, String password, Boolean voted) {
this.id = id;
this.username = username;
this.email = email;
this.password = password;
this.voted = voted;
}
public UserDTO(User user) {
id = user.getId();
username = user.getUsername();
email = user.getEmail();
password = user.getPassword();
voted = user.getVoted();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Boolean getVoted() {
return voted;
}
public void setVoted(Boolean voted) {
this.voted = voted;
}
}
UserServices.java
package com.dbserver.restaurantes.services;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dbserver.restaurantes.entities.User;
import com.dbserver.restaurantes.exceptions.HttpClientErrorException;
import com.dbserver.restaurantes.repositories.UserRepository;
#Service
public class UserServices {
#Autowired
private UserRepository repository;
PasswordEncoder passwordEncoder;
public UserServices(UserRepository userRepository) {
this.passwordEncoder = new BCryptPasswordEncoder();
}
#SuppressWarnings("rawtypes")
#Transactional(readOnly = true)
public List<User> findAllUsers(List list) {
List<User> result = repository.findAll();
return result;
}
#Transactional
public User addUser(User newUser) {
if (repository.findByEmail(newUser.getEmail()) != null) {
throw new HttpClientErrorException("O e-mail informado já existe no sistema");
}
String encodedPassword = this.passwordEncoder.encode(newUser.getPassword());
newUser.setPassword(encodedPassword);
return repository.saveAndFlush(newUser);
}
#Scheduled(cron = "0 00 13* * *")
public void resetVotes() throws InterruptedException {
List<User> userArray = repository.findAll();
for(User user: userArray ) {
user.setVoted(false);
}
}
}
UserRepository.java
package com.dbserver.restaurantes.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.dbserver.restaurantes.entities.User;
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
}
UserController.java
package com.dbserver.restaurantes.controllers;
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;
import com.dbserver.restaurantes.entities.User;
import com.dbserver.restaurantes.services.UserServices;
#RestController
#RequestMapping(value = "/users")
public class UserController {
#Autowired
private UserServices service;
#PostMapping
public User addUser(#RequestBody User newUser) {
return service.addUser(newUser);
}
}
I think you need to re-update the user list after setVoted(false)
#Scheduled(cron = "0 00 13* * *")
public void resetVotes() throws InterruptedException {
List<User> userArray = repository.findAll();
for(User user: userArray ) {
user.setVoted(false);
}
repository.save(userArray);
}
You dont need to load all user from db.
You can just update data by a custom query.
#Scheduled(cron = "0 00 13* * *")
public void resetVotes() throws InterruptedException {
repository.resetVotes();
}
UserRepository.java
package com.dbserver.restaurantes.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.dbserver.restaurantes.entities.User;
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
//update custom query
#Modifying
#Query("update User set voted=false ")
int resetVotes();
}
I'm trying to sort of login with JPA and hibernate. The truth is that I'm new to working with hibernate and I don't know what I'm doing wrong.
I have two entity classes (User and Credential), and I have already mapped them in the persistence.xml file
<!-- Define Persistence Unit -->
<persistence-unit name="HibernateSchedule" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>ues.edu.sv.entity.User</class>
<class>ues.edu.sv.entity.Credential</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/diary?useSSL=false&useTimezone=true&serverTimezon=UTC&allowPublicKeyRetrieval=true"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="localhost"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
These are the entity classes:
package ues.edu.sv.entity;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#NamedQueries({
#NamedQuery(name="User.listAllUsers", query="SELECT u FROM User u")
})
#Table(name = "\"user\"")
public class User implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id_user")
private int idUser;
private String name;
#Column(name = "lastname")
private String lastName;
private String email;
public User(){}
public User(int idUser){
this.idUser = idUser;
}
public User(String name, String lastName, String email){
this.name = name;
this.lastName = lastName;
this.email = email;
}
public User(int idUser, String name, String lastName, String email){
this.idUser = idUser;
this.name = name;
this.lastName = lastName;
this.email = email;
}
public int getIdUser() {
return idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User{" + "idUser=" + idUser + ", name=" + name + ", lastName=" + lastName + ", email=" + email + '}';
}
}
This is the Credential class
package ues.edu.sv.entity;
import java.io.Serializable;
import javax.persistence.*;
#Entity
#NamedQueries({
#NamedQuery(name = "Credential.getAllCredentials", query = "SELECT c FROM Credential
c")
})
#Table(name = "credential")
public class Credential implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id_credential")
private int idCredential;
#Column(name = "username")
private String userName;
private String password;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "id_user", referencedColumnName = "id_user")
private User user;
public Credential(){}
public Credential(int idCredential){
this.idCredential = idCredential;
}
public Credential(String userName, String password){
this.userName = userName;
this.password = password;
}
public Credential(String userName, String password, User user){
this.userName = userName;
this.password = password;
this.user = user;
}
public Credential(int idCredential,String userName, String password){
this.idCredential = idCredential;
this.userName = userName;
this.password = password;
}
public int getIdCredential() {
return idCredential;
}
public void setIdCredential(int idCredential) {
this.idCredential = idCredential;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public String toString() {
return "Credential{" + "idCredential=" + idCredential + ", userName=" + userName + ", password=" + password + ", user=" + user + '}';
}
}
I am using a three layer pattern to retrieve the information, so I have a package "ues.edu.sv.dao" where I have two interfaces and two classes that implement them and are defined as ejb
package ues.edu.sv.dao;
import java.util.List;
import ues.edu.sv.entity.User;
public interface UserDao {
public List<User> listAllUsers();
public User getUserById(User user);
public void createNewUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
}
package ues.edu.sv.dao;
import java.util.List;
import ues.edu.sv.entity.Credential;
public interface CredentialDao {
public List<Credential> getAllCredentials();
public Credential getCredentialById(Credential credential);
public Credential getCredentialByUserName(Credential credential);
public void createNewCredential(Credential credential);
public void updateCredential(Credential credential);
public void deleteCredential(Credential credential);
}
And here are the classes that implement their corresponding interface
package ues.edu.sv.dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.*;
import ues.edu.sv.entity.User;
#Stateless
public class UserDaoImpl implements UserDao {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("HibernateSchedule");
EntityManager em = emf.createEntityManager();
#Override
public List<User> listAllUsers() {
return em.createNamedQuery("User.listAllUsers").getResultList();
}
#Override
public User getUserById(User user) {
return em.find(User.class, user.getIdUser());
}
#Override
public void createNewUser(User user) {
em.persist(user);
}
#Override
public void updateUser(User user) {
em.merge(user);
}
#Override
public void deleteUser(User user) {
em.remove(em.merge(user));
}
}
package ues.edu.sv.dao;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import ues.edu.sv.entity.Credential;
#Stateless
public class CredentialDaoImpl implements CredentialDao {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory("HibernateSchedule");
EntityManager em = emf.createEntityManager();
#Override
public List<Credential> getAllCredentials() {
return em.createNamedQuery("Credential.getAllCredentials").getResultList();
}
#Override
public Credential getCredentialById(Credential credential) {
return em.find(Credential.class, credential.getIdCredential());
}
#Override
public Credential getCredentialByUserName(Credential credential) {
return em.find(Credential.class, credential.getUserName());
}
#Override
public void createNewCredential(Credential credential) {
em.persist(credential);
}
#Override
public void updateCredential(Credential credential) {
em.merge(credential);
}
#Override
public void deleteCredential(Credential credential) {
em.remove(em.merge(credential));
}
}
My understanding is that since I am working in a java enterprise context, there is no need to open a transaction when persisting an object in the database. I am using glassfish by the way.
now to complete the three-layer pattern, I have another package called "ues.edu.sv.service" that injects the above interfaces via CDI
package ues.edu.sv.service;
import java.util.List;
import javax.ejb.Local;
import ues.edu.sv.entity.Credential;
#Local
public interface CredentialService {
public List<Credential> getAllCredentials();
public Credential getCredentialById(Credential credential);
public Credential getCredentialByUserName(Credential credential);
public void createNewCredential(Credential credential);
public void updateCredential(Credential credential);
public void deleteCredential(Credential credential);
}
package ues.edu.sv.service;
import java.util.List;
import javax.ejb.Local;
import ues.edu.sv.entity.User;
#Local
public interface UserService {
public List<User> listAllUsers();
public User getUserById(User user);
public void createNewUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
}
and implementation classes
package ues.edu.sv.service;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.inject.Inject;
import ues.edu.sv.dao.CredentialDao;
import ues.edu.sv.entity.Credential;
#Stateless
public class CredentialServiceImpl implements CredentialService{
#Inject
CredentialDao credentialDao;
#Resource
SessionContext context;
#Override
public List<Credential> getAllCredentials() {
return credentialDao.getAllCredentials();
}
#Override
public Credential getCredentialById(Credential credential) {
return credentialDao.getCredentialById(credential);
}
#Override
public Credential getCredentialByUserName(Credential credential) {
return credentialDao.getCredentialByUserName(credential);
}
#Override
public void createNewCredential(Credential credential) {
credentialDao.createNewCredential(credential);
}
#Override
public void updateCredential(Credential credential) {
try{
credentialDao.updateCredential(credential);
}catch(Exception ex){
ex.printStackTrace(System.out);
context.setRollbackOnly();
}
}
#Override
public void deleteCredential(Credential credential) {
credentialDao.deleteCredential(credential);
}
}
package ues.edu.sv.service;
import java.util.List;
import javax.annotation.Resource;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.inject.Inject;
import ues.edu.sv.dao.UserDao;
import ues.edu.sv.entity.User;
#Stateless
public class UserServiceImpl implements UserService{
#Inject
UserDao userDao;
#Resource
SessionContext context;
#Override
public List<User> listAllUsers() {
return userDao.listAllUsers();
}
#Override
public User getUserById(User user) {
return userDao.getUserById(user);
}
#Override
public void createNewUser(User user) {
userDao.createNewUser(user);
}
#Override
public void updateUser(User user) {
try{
userDao.updateUser(user);
}catch(Exception ex){
ex.printStackTrace(System.out);
context.setRollbackOnly();
}
}
#Override
public void deleteUser(User user) {
userDao.deleteUser(user);
}
}
And finally I have an ejb that connects to the jsf page called "Register.xhtml" and is responsible for retrieving the information that the user enters in the text fields to finally persist the information in the database, I have programmed the relationships so cascading user object can be persisted
package ues.edu.sv.beans;
import java.io.IOException;
import javax.enterprise.context.RequestScoped;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.inject.Named;
import ues.edu.sv.crypto.Cypher;
import ues.edu.sv.entity.Credential;
import ues.edu.sv.entity.User;
import ues.edu.sv.service.CredentialService;
import ues.edu.sv.service.UserService;
#Named
#RequestScoped
public class RegisterBean {
#Inject
CredentialService credentialService;
#Inject
UserService userService;
private String name;
private String lastName;
private String email;
private String userName;
private String password;
public RegisterBean() {
}
public void toRegister() {
User user = new User(name, lastName, email);
String encriptedPassword = Cypher.encryptPassword(password);
Credential credential = new Credential(userName, encriptedPassword, user);
credentialService.createNewCredential(credential);
try {
FacesContext.getCurrentInstance().getExternalContext().redirect("Login.xhtml");
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And apparently everything is fine, the console does not show me any error, but it does nothing in the database, it does not insert the content into the database :(
This is what appears in the console when everything has been executed...
]|#]
HHH000204: Processing PersistenceUnitInfo [name: HibernateSchedule]|#]
HHH000412: Hibernate Core {6.0.0.Alpha4}|#]
HCANN000001: Hibernate Commons Annotations {5.1.0.Final}|#]
HHH10001002: Using Hibernate built-in connection pool (not for production use!)|#]
HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL
[jdbc:mysql://localhost:3306/diary?
useSSL=false&useTimezone=true&serverTimezon=UTC&allowPublicKeyRetrieval=true]|#]
HHH10001001: Connection properties: {user=root, password=****}|#]
HHH10001003: Autocommit mode: false|#]
HHH000115: Hibernate connection pool size: 20 (min=1)|#]
HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect|#]
HHH10005002: No explicit CDI BeanManager reference was passed to Hibernate, but CDI
is available on the Hibernate ClassLoader.|#]
HHH000490: Using JtaPlatform implementation:
[org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]|#]
That is all that appears. Someone who can help me please
I am developing a project in which one of the many requirement is to custom validate the two objects for which I am passing both objects to the controller from a single form.
I am frequently receiving the exception on the particular statement which I don't know how to manage or solve it.
package com.practive.course.configure;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.practive.course.model.Credentials;
import com.practive.course.model.Student;
#Component
public class StudentValidator implements Validator {
private final Validator credentialValidator;
public StudentValidator(Validator credentialValidator) {
if (credentialValidator == null) {
throw new IllegalArgumentException(
"The supplied [Validator] is required and must not be null.");
}
if (!credentialValidator.supports(Credentials.class)) {
throw new IllegalArgumentException(
"The supplied [Validator] must support the validation of [Address] instances.");
}
this.credentialValidator = credentialValidator;
}
/**
* This Validator validates Customer instances, and any subclasses of Customer too
*/
public boolean supports(Class clazz) {
return Student.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
Student student = (Student) target;
System.out.println(student.getMyname());
System.out.println("below");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotEmpty"); //this line generates the exception
System.out.println("above");
//ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "field.required");
try {
errors.pushNestedPath("credentials");
ValidationUtils.invokeValidator(this.credentialValidator, student.getCred(), errors);
} finally {
errors.popNestedPath();
}
}
}
#PostMapping("/registration")
public String postRegister(Student student,Credentials credential,BindingResult bindingResult,RedirectAttributes redirect) {
try{
validator.validate(student,bindingResult);
}catch(Exception e) {
System.out.println("problem is here "+e.getMessage());
}
try {
if(bindingResult.hasErrors()) {
return "registration";
}
}catch(Exception e) {
System.out.println("problem is in biding "+e.getMessage());
}
appService.registerStudent(student,credential);
return "redirect:/login";
}
package com.practive.course.model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
#Entity
public class Student {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String myname;
private String mobile;
private String email;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="credid")
private Credentials cred;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getMyname() {
return myname;
}
public void setMyname(String myname) {
this.myname = myname;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Credentials getCred() {
return cred;
}
public void setCred(Credentials cred) {
this.cred = cred;
}
}
package com.practive.course.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Credentials {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String username;
private String password;
private String usermobile;
private Role roles;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsermobile() {
return usermobile;
}
public void setUsermobile(String usermobile) {
this.usermobile = usermobile;
}
public Role getRoles() {
return roles;
}
public void setRoles(Role roles) {
this.roles = roles;
}
}
The stacktrace :
Invalid property 'email' of bean class [com.practive.course.model.Credentials]: Bean property 'email' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
The above exception is being generated when I am trying to validate
The stacktrace shows that Invalid property 'email' of bean class [com.practive.course.model.Credentials] , the validator method is trying to get the email property of the Credentials object while from your code it is visible that the "email" is part of the Student class.
I am trying to insert the date into database and I am using java.sql.Date but the problem when user is submitting the form I am getting Null value. As per some restriction I am only allowed to use java.sql.Date not util.Date.
Entity
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
#Entity
#Table(name="Users")
public class Users {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="User_ID")
private int ID;
#Column(name="User_first_name")
#NotEmpty(message="Field cannot be left blank")
private String First_Name;
#Column(name="user_last_name")
private String Last_Name;
#Column(name="user_contact")
private int Contact;
#Column(name="user_email")
private String Email;
#Column(name="user_date_birth")
#DateTimeFormat(pattern="dd/MM/yyyy")
private Date DateOfBirth;
#Column(name="user_joining_date")
private Date DateOfJoining;
#Column(name="user_salary")
#NotNull
private int Salary;
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getFirst_Name() {
return First_Name;
}
public void setFirst_Name(String first_Name) {
First_Name = first_Name;
}
public String getLast_Name() {
return Last_Name;
}
public void setLast_Name(String last_Name) {
Last_Name = last_Name;
}
public int getContact() {
return Contact;
}
public void setContact(int contact) {
Contact = contact;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public Date getDateOfBirth() {
return DateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
DateOfBirth = dateOfBirth;
}
public Date getDateOfJoining() {
return DateOfJoining;
}
public void setDateOfJoining(Date dateOfJoining) {
DateOfJoining = dateOfJoining;
}
public int getSalary() {
return Salary;
}
public void setSalary(int salary) {
Salary = salary;
}
}
Controller
package com.example.crud;
import java.text.SimpleDateFormat;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.example.crud.entities.Users;
import com.example.crud.service.TaskService;
#Controller
public class HomeController {
#Autowired
private TaskService service;
private Logger logger = LoggerFactory.getLogger(HomeController.class);
#InitBinder
public void initBinder(WebDataBinder binder){
System.out.println("exe");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
sdf.setLenient(true);
binder.registerCustomEditor(java.sql.Date.class,"DateOfBirth", new CustomDateEditor(sdf, true));
}
#RequestMapping(value="/Add", method=RequestMethod.GET)
public String index(Map<String, Object> model){
Users users = new Users();
model.put("users", users);
logger.debug("users");
return "home";
}
#RequestMapping(value="/Register", method=RequestMethod.POST)
public String Register(#ModelAttribute("users") Users users, BindingResult result, Model model){
System.out.println(users.getFirst_Name());
System.out.println(users.getDateOfBirth());
// service.Register(users);
return "home";
}
}
Register your own custom editor.
public class SqlDateEditor extends PropertyEditorSupport {
private DateFormat dateFormat;
public SqlDateEditor (final DateFormat dateFormat)
{
this.dateFormat = dateFormat;
}
#Override
public void setAsText(String text) {
try {
setValue(new java.sql.Date(this.dateformat.parse(text).getTime())
} catch (ParseException e) {
throw new IllegalArgumentException("Could not parse date: " + e.getMessage());
}
}
#Override
public String getAsText() {
java.sql.Date value = (java.sql.Date) getValue();
return (value != null ? this.dateFormat.format(value) : "");
}
}
At your controller:
#InitBinder
public void initBinder(final WebDataBinder binder) {
binder.registerCustomEditor(java.sql.Date.class, new SqlDateEditor(new SimpleDateFormat("dd/MM/yyyy")));
}
Given the following class:
package com.example.model;
import java.util.Collection;
import java.util.Set;
import org.neo4j.graphdb.Direction;
import org.neo4j.helpers.collection.IteratorUtil;
import org.springframework.data.neo4j.annotation.Indexed;
import org.springframework.data.neo4j.annotation.NodeEntity;
import org.springframework.data.neo4j.annotation.RelatedTo;
import org.springframework.data.neo4j.annotation.RelatedToVia;
import org.springframework.security.core.GrantedAuthority;
#NodeEntity
public class User {
private static final String SALT = "cewuiqwzie";
public static final String FRIEND = "FRIEND";
public static final String RATED = "RATED";
#Indexed
String login;
String name;
String password;
String info;
private Roles[] roles;
public User() {
}
public User(String login, String name, String password, Roles... roles) {
this.login = login;
this.name = name;
this.password = encode(password);
this.roles = roles;
}
private String encode(String password) {
return "";
// return new Md5PasswordEncoder().encodePassword(password, SALT);
}
#RelatedToVia(elementClass = Rating.class, type = RATED)
Iterable<Rating> ratings;
#RelatedTo(elementClass = Movie.class, type = RATED)
Set<Movie> favorites;
#RelatedTo(elementClass = User.class, type = FRIEND, direction = Direction.BOTH)
Set<User> friends;
public void addFriend(User friend) {
this.friends.add(friend);
}
public Rating rate(Movie movie, int stars, String comment) {
return relateTo(movie, Rating.class, RATED).rate(stars, comment);
}
public Collection<Rating> getRatings() {
return IteratorUtil.asCollection(ratings);
}
#Override
public String toString() {
return String.format("%s (%s)", name, login);
}
public String getName() {
return name;
}
public Set<User> getFriends() {
return friends;
}
public Roles[] getRole() {
return roles;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public void updatePassword(String old, String newPass1, String newPass2) {
if (!password.equals(encode(old)))
throw new IllegalArgumentException("Existing Password invalid");
if (!newPass1.equals(newPass2))
throw new IllegalArgumentException("New Passwords don't match");
this.password = encode(newPass1);
}
public void setName(String name) {
this.name = name;
}
public boolean isFriend(User other) {
return other != null && getFriends().contains(other);
}
public enum Roles implements GrantedAuthority {
ROLE_USER, ROLE_ADMIN;
#Override
public String getAuthority() {
return name();
}
}
}
I get a compilation exception here:
public Rating rate(Movie movie, int stars, String comment) {
return relateTo(movie, Rating.class, RATED).rate(stars, comment);
}
Following the tutorial here. Any insight as to where this function resides is appreciated.
You're trying to use the advanced mapping mode. See the reference manual for more information. You'll need to set up AspectJ support in your IDE. Methods are woven into your entity classes at compile time.