Hibernate does not insert the information into the database - java

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

Related

#Scheduled not updating my JSON values to FALSE

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();
}

How to validate the Nested Objects using Spring Validation in Spring boot?

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.

custom converter not called spring data mongodb [can't serialize class error]

I have a User bean with a property address. I have implemented custom converter for the User and the Address class and configured the same in spring XML. The converter for User is getting called every time I save User object. But, converter for Address is not getting called while saving the User and it throwing can't serialize class com.mkyong.model.Address.
Here is my class structure and Xml config:
User Class:
package com.mkyong.model;
import java.util.Map;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "person")
public class User {
#Id
private String id;
String username;
String password;
Address address;
Map data;
public String getId() {
return id;
}
public void setId(String 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 Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Map getData() {
return data;
}
public void setData(Map data) {
this.data = data;
}
public User(String username, String password) {
super();
this.username = username;
this.password = password;
}
#Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}
Address class :
package com.mkyong.model;
import java.io.Serializable;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "address")
public class Address implements Serializable {
/**
*
*/
private static final long serialVersionUID = 2310280839505243479L;
String city;
String dist;
String state;
public Address(String city, String dist, String state) {
super();
this.city = city;
this.dist = dist;
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getDist() {
return dist;
}
public void setDist(String dist) {
this.dist = dist;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
#Override
public String toString() {
return "Address [city=" + city + ", dist=" + dist + ", state=" + state + "]";
}
}
spring configuration:
<mongo:mongo host="127.0.0.1" port="27017" />
<mongo:db-factory dbname="springbootdb" />
<mongo:mapping-converter id="mongoConverter">
<mongo:custom-converters base-package="com.mkyong.model">
<mongo:converter>
<bean class="com.mkyong.converter.UserConverter" />
</mongo:converter>
<mongo:converter>
<bean class="com.mkyong.converter.AddressConverter" />
</mongo:converter>
</mongo:custom-converters>
</mongo:mapping-converter>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoConverter" ref="mongoConverter" />
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
User Converter :
package com.mkyong.converter;
import org.springframework.core.convert.converter.Converter;
import com.mkyong.model.User;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
public class UserConverter implements Converter<User, DBObject> {
#Override
public DBObject convert(User user) {
DBObject dbObject = new BasicDBObject();
dbObject.put("_id", user.getId());
dbObject.put("_address", user.getAddress());
System.out.println("called !!!!!");
return dbObject;
}
}
Address Converter :
package com.mkyong.converter;
import org.springframework.core.convert.converter.Converter;
import com.mkyong.model.Address;
import com.mkyong.model.DecimalNumber;
import com.mkyong.model.User;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
public class AddressConverter implements Converter<Address, String> {
#Override
public String convert(Address user) {
System.out.println("Not called!!!");
return user==null ? null : user.toString();
}
}
I am very new to spring mongodb. Any help is greatly appreciated!
Please annotate UserConverter with #Component so that your converter will be picked by Spring Container.

Spring MVC application

Hi all I´m learning how to use Spring, I don´t have experience in MVC.
So I´m making a website who makes registrations, de-registrations and changes in the data of a mysql database.
The login and inserts to DB are ready but I can't make the delete registered user part.
My model:
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class StudentDelete {
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
#Size(min=4, max=8)
private String password;
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
My Controller:
#Controller
#SessionAttributes("student")
public class StudentController {
#Autowired
private StudentService studentService;
#RequestMapping(value="/delete", method=RequestMethod.GET)
public String delete(Model model) {
Student studentDelete = new Student();
model.addAttribute("studentDelete", studentDelete);
return "delete";
}
blablabla
#RequestMapping(value="/delete", method=RequestMethod.POST)
public String delete(#Valid #ModelAttribute("studentDelete") StudentDelete studentDelete, BindingResult result) {
if (result.hasErrors()) {
return "delete";
} else {
boolean found = studentService.findByLogin(studentDelete.getUserName(), studentDelete.getPassword());
if (found) {
studentService.deleteByLogin(studentDelete.getUserName(), studentDelete.getPassword());
return "successD";
} else {
return "failureD";
}
}
}
My Service and the implementation:
package com.github.elizabetht.service;
import com.github.elizabetht.model.Student;
public interface StudentService {
Student save(Student student);
boolean findByLogin(String userName, String password);
boolean findByUserName(String userName);
boolean deleteByLogin(String userName, String password);
}
Implementation:
public boolean deleteByLogin(String userName, String password) {
StudentDelete stud = studentDeleteRepository.deleteByLogin(userName, password);
if(stud != null) {
return true;
}
return false;
}
And finally The StudentDeleteRepository:
package com.github.elizabetht.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.github.elizabetht.model.Student;
import com.github.elizabetht.model.StudentDelete;
#Repository("studentDeleteRepository")
public interface StudentDeleteRepository extends JpaRepository<StudentDelete, Long> {
#Query("delete s from Student s where s.userName = :userName and s.password = :password")
StudentDelete deleteByLogin(#Param("userName") String userName, #Param("password") String password);
}
StudentRepository.java
package com.github.elizabetht.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.github.elizabetht.model.Student;
#Repository("studentRepository")
public interface StudentRepository extends JpaRepository<Student, Long> {
#Query("select s from Student s where s.userName = :userName")
Student findByUserName(#Param("userName") String userName);
}
In my delete.jsp all starts with this:
<form:form id="myForm" method="post"
class="bs-example form-horizontal" commandName="studentDelete">
I'm getting this error:
java.lang.NullPointerException
com.github.elizabetht.service.StudentServiceImpl.deleteByLogin(StudentServiceImpl.java:47)
Which is this part:
StudentDelete stud = studentDeleteRepository.deleteByLogin(userName, password);
Why it doesnt happen with the save method?
Any help is appreciated.
Thanks!
Your issue is that parameter you are passing below:
StudentDelete stud = studentDeleteRepository.deleteByLogin(userName, password);
username or password are empty.
Hence the null pointer exception.
Change your implementation to following formate:
public boolean deleteByLogin(String userName, String password) {
if(userName == null || password == null)
return false; // it failed essentially
StudentDelete stud = studentDeleteRepository.deleteByLogin(userName, password);
if(stud != null) {
return true;
}
return false;
}
I think the error you specified in the comments:
Not a managed type: class com.github.elizabetht.model.StudentDelete
is because you are missing the JPA #Entity annotation on your model class:
import javax.validation.constraints.Size;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
#Table("student")
public class StudentDelete {
#NotEmpty
#Size(min=4, max=20)
private String userName;
#NotEmpty
#Size(min=4, max=8)
private String password;
public String getPassword() {
return password;
}
public String getUserName() {
return userName;
}
public void setPassword(String password) {
this.password = password;
}
public void setUserName(String userName) {
this.userName = userName;
}
}

Google App Engine User Registration System

I am creating a user registration system in google app engine, and so far I could develop the registration side of the app. But I can't log in and create a HttpSession.
Here what I did, I created login.jsp and two text boxes to input email and password.
And then I created Bean class and DAO class as following.
package com.myfirstguide.beans;
import javax.servlet.http.HttpSession;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
public class UserDAO {
public static UserBean login(UserBean bean){
String email = bean.getEmail();
String password = bean.getPassword();
try{
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Query q = new Query("Account");
q.addFilter("email", Query.FilterOperator.EQUAL, email);
q.addFilter("password", Query.FilterOperator.EQUAL, password);
PreparedQuery pq = datastore.prepare(q);
Entity result = pq.asSingleEntity();
if(result != null){
bean.setValid(true);
}
//return bean;
}catch(Exception e){
}
return bean;
}
}
Here is the Bean class.
package com.myfirstguide.beans;
public class UserBean {
private String username;
private String password;
private String firstName;
private String lastName;
private String email;
public boolean valid;
public String getFirstName() {
return firstName;
}
public void setFirstName(String newFirstName) {
firstName = newFirstName;
}
public void setEmail(String semail){
email = semail;
}
public String getEmail(){
return email;
}
public String getLastName() {
return lastName;
}
public void setLastName(String newLastName) {
lastName = newLastName;
}
public String getPassword() {
return password;
}
public void setPassword(String newPassword) {
password = newPassword;
}
public String getUsername() {
return username;
}
public void setUserName(String newUsername) {
username = newUsername;
}
public boolean isValid() {
return valid;
}
public void setValid(boolean newValid) {
valid = newValid;
}
}
And here is the Servlet.
package com.myfirstguide.users;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.myfirstguide.beans.UserBean;
import com.myfirstguide.beans.UserDAO;
public class SignIn extends HttpServlet{
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String email = req.getParameter("email");
String password = req.getParameter("password");
try{
UserBean ubean = new UserBean();
ubean.setEmail(email);
ubean.setPassword(password);
ubean = UserDAO.login(ubean);
if(ubean.isValid()){
HttpSession session = req.getSession(true);
session.setAttribute("currentSessionUser",ubean);
resp.sendRedirect("index.jsp?session=" + ubean.getFirstName()); //logged-in page
}
}catch(Throwable e){
System.out.println(e);
}
}
}
And I don't know JPA. And if there is better way to do this, please tell me.
Thank you!
Have you enabled sessions?
https://developers.google.com/appengine/docs/java/config/appconfig#Enabling_Sessions

Categories

Resources