I want retrieve user email from MySql database table using spring boot.i used findByEmailAndPassword in controller but it retrieve null value for email.
Here is my Code
controller
package com.example.demo.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.example.demo.JPARepository;
import com.example.demo.pojo.regisbean;
#Controller
public class registerController {
regisbean pp;
#RequestMapping(value = "/")
public String mm() {
System.out.println("I am in m1 method");
return "index";
}
#RequestMapping(value = { "/register", "home" })
public String m1() {
System.out.println("I am in mm method");
return "register";
}
#Autowired
JPARepository jpaRepository;
#PostMapping("/register")
public String regis(#ModelAttribute regisbean rb)
{
System.out.println("I m in regis method");
regisbean b=jpaRepository.save(rb);
if(b!=null)
return "index";
else
return "fail";
}
#RequestMapping(value= {"/login1","login2"})
public String m2() {
System.out.println("i m in m2()");
return "login";
}
#PostMapping("/login")
public String login(#ModelAttribute regisbean rx,Model m) {
System.out.println("I am in Login");
regisbean re=jpaRepository.findByEmailAndPassword(rx.getEmail(), rx.getPassword());
if(re!=null)
{
m.addAttribute("email",rx.getEmail());
m.addAttribute("password",rx.getPassword());
System.out.println("yes");
return "loginsuccess";
}
else
{
System.out.println(rx.getEmail());
System.out.println("failed");
return "register";
}
}
}
pojo class
package com.example.demo.pojo;
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 = "pro")
public class regisbean {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column
private String name;
#Column
private String email;
#Column
private String phonenumber;
#Column
private String password;
public int getId() {
return id;
}
public void setId(int 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 getPhonenumber() {
return phonenumber;
}
public void setPhonenumber(String phonenumber) {
this.phonenumber = phonenumber;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Repository
package com.example.demo;
import org.springframework.data.repository.CrudRepository;
import com.example.demo.pojo.regisbean;
public interface JPARepository extends CrudRepository<regisbean, Integer> {
public regisbean findByEmailAndPassword(String email,String password);
}
I was able to get your code to work by inserting a row in the table:
INSERT INTO pro (
id
,email
,name
,password
,phonenumber
)
VALUES (
0
,'user#domain.com'
,'Jim'
,'secret'
,'123-123-1234'
)
Then changing:
public String login(#ModelAttribute regisbean rx,Model m) {
to:
public String login(#RequestBody RegisBean rx,Model m) {
and POSTing the following request body to the /login resource:
{
"email": "user#domain.com",
"password": "secret"
}
I didn't have to make any changes to your Repo. I suspect your attempt was failing because RegisBean was never being initialized with any values and so the repo was asked to find a record with a null email and a null password.
Related
I am making authorization for a web application. And I an faced witw problem. I can not use Getters and Setters. Namely setActive ans setRole. And I can not create variable UserFromDb.
RegistrationController.java
import com.Vova.Restart.Models.Role;
import com.Vova.Restart.repo.UserRepo;
import org.springframework.security.core.userdetails.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.Collections;
import java.util.Map;
#Controller
public class RegistrationController {
#Autowired
private UserRepo userRepo;
#GetMapping("/registration")
public String registration() {
return "registration";
}
#PostMapping("/registration")
public String addUser (User user, Map<String, Object> model) {
userFromDb = userRepo.findByUsername(user.getUsername());
if (userFromDb != null) {
model.put("message", "User exists!");
return "registration";
}
user.setActive(true);
user.setRole(Collections.singleton(Role.USER));
return "redirect:/login";
}
}
User.java
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name = "User")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username, password;
private boolean active;
#ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
#CollectionTable(name = "userRole", joinColumns = #JoinColumn(name = "userId"))
#Enumerated(EnumType.STRING)
private Set<Role> roles;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
public void setRole(Set<Object> singleton) {
}
}
I tried to use import com.Vova.Restart.Models.User instead import org.springframework.security.core.userdetails.User and this error has gone but i get another problem Not a managed type: class org.springframework.security.core.userdetails.User. I think this is wrong imort. How can i solve it?
I am not sure why I get this error but I suspect that it is from the TestApplication.java. I've tried various things like, Question1, but cannot figure out what is wrong.
I referenced this video to build this application.
ERROR
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.example.User.UserService required a bean
of type 'com.example.User.UserRepository' that could not be found.
Action:
Consider defining a bean of type 'com.example.User.UserRepository' in your
configuration.
TestApplication.java
package com.example.test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import com.example.User.UserController;
#SpringBootApplication
#ComponentScan(basePackageClasses = {UserController.class})
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
User.java
package com.example.User;
import java.time.LocalDate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
#Entity
#Table(name = "USER")
public class User {
#Id
#SequenceGenerator(
name = "user_sequence",
sequenceName = "user_sequence",
allocationSize = 1
)
#GeneratedValue(
strategy = GenerationType.SEQUENCE,
generator = "user_sequence"
)
private Long id;
private String PDGA_id;
private String first_name;
private String last_name;
private String email;
private boolean email_verified;
private String phone_number;
private String password;
private LocalDate created_date;
private LocalDate modified_date;
public User(){
}
public User(Long id,
String PDGA_id,
String first_name,
String last_name,
String email,
boolean email_verified,
String phone_number,
String password,
LocalDate created_date,
LocalDate modified_date)
{
this.id = id;
this.PDGA_id = PDGA_id;
this.first_name = first_name;
this.last_name = last_name;
this.email = email;
this.email_verified = email_verified;
this.phone_number = phone_number;
this.password = password;
this.created_date = created_date;
this.modified_date = modified_date;
}
public User(String PDGA_id,
String first_name,
String last_name,
String email,
boolean email_verified,
String phone_number,
String password,
LocalDate created_date,
LocalDate modified_date)
{
this.PDGA_id = PDGA_id;
this.first_name = first_name;
this.last_name = last_name;
this.email = email;
this.email_verified = email_verified;
this.phone_number = phone_number;
this.password = password;
this.created_date = created_date;
this.modified_date = modified_date;
}
// Getter-Setter
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getPDGA_id() {
return this.PDGA_id;
}
public void setPDGA_id(String PDGA_id) {
this.PDGA_id = PDGA_id;
}
public String getFirst_name() {
return this.first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return this.last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEmail_verified() {
return this.email_verified;
}
public void setEmail_verified(boolean email_verified) {
this.email_verified = email_verified;
}
public String getPhone_number() {
return this.phone_number;
}
public void setPhone_number(String phone_number) {
this.phone_number = phone_number;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public LocalDate getCreated_date() {
return this.created_date;
}
public void setCreated_date(LocalDate created_date) {
this.created_date = created_date;
}
public LocalDate getModified_date() {
return this.modified_date;
}
public void setModified_date(LocalDate modified_date) {
this.modified_date = modified_date;
}
#Override
public String toString(){
return "User{" +
"id =" + id +
", PDGA_id" + PDGA_id + '\'' +
", first_name" + first_name + '\'' +
", last_name" + last_name + '\'' +
", email" + email + '\'' +
", email_verified" + email_verified +
", phone_number" + phone_number + '\'' +
", password" + password + '\'' +
", created_date" + created_date +
", modified_date" + modified_date +
"}";
}
}
UserController.java
package com.example.User;
import java.util.List;
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;
#RestController
#RequestMapping(path = "api/v1/user")
public class UserController {
private final UserService userService;
#Autowired
public UserController(UserService userService){
this.userService = userService;
}
#GetMapping()
public List<User> getUsers(){
return userService.getUsers();
}
}
UserRepository.java
package com.example.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
UserService.java
package com.example.User;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
#Service
public class UserService {
private final UserRepository userRepository;
#Autowired
public UserService(UserRepository userRepository){
this.userRepository = userRepository;
}
public List<User> getUsers(){
return userRepository.findAll();
}
}
application.properties
spring.datasource.url=jdbc:mariadb://localhost:3306/LiensDiGoLinks
spring.datasource.username=root
spring.datasource.password=Password123!
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.properties.hibernate.format_sql=true
I have just started learning and experimenting with spring-boot and hibernate and there is this problem I can't seem to figure out.
package net.codejava;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase.Replace;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.annotation.Rollback;
#DataJpaTest
#AutoConfigureTestDatabase(replace = Replace.NONE)
#Rollback(false)
public class UserRepositoryTests {
#Autowired
private UserRepositoryTests repo;
#Autowired
private TestEntityManager entityManager;
#Test
public void testCreateUser() {
User user = new User();
user.setEmail("xyz#gmail.com");
user.setPassword("XYZ!##");
user.setFirstname("XYZ");
user.setLastname("PQR");
user.setUsername("XZY");
User savedUser = repo.save(user);
User existUser = entityManager.find(User.class, savedUser.getIdUser());
assertThat(user.getEmail()).isEqualTo(existUser.getEmail());
}
}
There is some error with line 38 (i.e,User savedUser = repo.save(user);)
is says that"The method save(User) is undefined for the type UserRepositoryTests"
User.java
package net.codejava;
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 = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idUser;
#Column(nullable = false,unique=true,length = 45)
private String email;
#Column(nullable = false,unique=true,length = 45)
private String firstname;
#Column(nullable = false,unique=true,length = 45)
private String lastname;
#Column(nullable = false,unique=true,length = 45)
private String username;
#Column(nullable = true)
private String IPaddress;
#Column(nullable = false,length = 64)
private String password;
public Long getIdUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getIPaddress() {
return IPaddress;
}
public void setIPaddress(String iPaddress) {
IPaddress = iPaddress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserRepository.java
package net.codejava;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
Please let me know what to do.
the problem was UserRepositoryTests it should have been UserRepository.
I am new to spring boot as after completing a crud function rest API in spring-boot I'm badly stuck in login rest API for android application where I just want to use email and password in POSTMAPPING. Please anyone could help me here?
Controller class
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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 demo.loginapi.main.model.UserModel;
import demo.loginapi.main.repository.UserRepository;
import demo.loginapi.main.repository.UserService;
#RestController
#RequestMapping("/api/user")
public class UserController {
#Autowired
UserRepository userRepository;
#Autowired
UserService userService;
#GetMapping("/getallusers")
public List<UserModel> getAllCustomer(){
List<UserModel> alluserlist = userRepository.findAll();
return alluserlist;
}
#PostMapping("/login/{email}")
public List<UserModel> getemailpassword(#PathVariable(value = "email") String email){
List<UserModel> alluseremailpassword = userRepository.findUserByEmail(email);
return alluseremailpassword;
}
#PostMapping("/login2/{email}")
public UserModel getuserbyemail(#PathVariable(value = "email") String email)
{
UserModel userByEmailForLogin = userRepository.findByEmail(email);
return userByEmailForLogin;
}
#PostMapping("/loginemailpass/{email}/{password}")
public ResponseEntity<Map<String, String>> loginUser(#RequestBody Map<String, Object> userMap){
String email = (String) userMap.get("email");
String password = (String) userMap.get("password");
UserModel userModel = userService.validate(email,password);
return new ResponseEntity<>(generateJWTToken(userModel),HttpStatus.OK);
}
private Map<String, String> generateJWTToken(UserModel userModel) {
// TODO Auto-generated method stub
return null;
}
}
** Entity Class **
package demo.loginapi.main.model;
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 = "user_login")
public class UserModel {
#Id
#Column(name = "userId", nullable = false)
#GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
#Column(name = "username", nullable = false)
private String username;
#Column(name = "email", nullable = false)
private String email;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "role", nullable = false)
private String role;
public UserModel() {
//default constructor
}
public UserModel(Long userId, String username, String email, String password, String role) {
//super();
this.userId = userId;
this.username = username;
this.email = email;
this.password = password;
this.role = role;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
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 String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
#Override
public String toString() {
return "UserModel [userId=" + userId + ", username=" + username + ", email=" + email + ", password=" + password
+ ", role=" + role + "]";
}
}
** Repository Class **
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import demo.loginapi.main.model.UserModel;
#Repository
public interface UserRepository extends JpaRepository<UserModel, Long>{
List<UserModel> findUserByEmail(String email);
UserModel findByEmail(String email);
//UserModel validate(String email, String password);
UserModel findByEmailAndPaswword(String email, String password);
//UserModel findByEmailPassword(String email, String password);
}
** Service Class **
import demo.loginapi.main.model.UserModel;
public interface UserService {
UserModel validate(String email, String password);
}
** Service Implementation **
package demo.loginapi.main.repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import demo.loginapi.main.model.UserModel;
#Service
public class UserRepoImpl implements UserService{
#Autowired
UserRepository userRepository;
#Override
public UserModel validate(String email, String password) {
if(email != null) email = email.toLowerCase();
return userRepository.findByEmailAndPaswword(email, password);
}
}
In your repository class , is findByEmailAndPassword is available in jparepository, if not use through #query annotation like #query("select usename from userlogin us where us.username =:email") Something like that in your method.
Also if pre defined method is available please check the spelling, seems incorrect. It has double w in it. findByEmailAndPaswword
This question already has answers here:
Spring Boot Hibernate 5 Ignoring #Table and #Column
(2 answers)
Closed 5 years ago.
I try to use CrudRepository on my work. And When the sql request appear on my log, It's just abnormal.
The real table is 'AllDatabase.AllUserInfo' but the generated sql request look like 'all_user_info alluresinf0_', which is unusable.
I have been all over the internet and nobody seems to face my problem (as far as I know). So please somebody tell me if I'm missing some configuration in my project.
I work on Intellij Idea with 'Spring Initializer' with 'Web' , 'JPA' , 'MySQL' selected. These are my code.
here is my Repository
package com.chuchurest.proj.Repository;
import com.chuchurest.proj.Entity.AllUserInfo;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by slimshady23 on 6/25/2017 AD.
*/
#Transactional
#Repository
public interface UserRepository extends CrudRepository<AllUserInfo,String> {
}
here is The 'AllUserInfo' Entity
package com.chuchurest.proj.Entity;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import java.io.Serializable;
/**
* Created by slimshady23 on 6/23/2017 AD.
*/
#Entity
#Table(name = "AllUserInfo")
public class AllUserInfo {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private String Id;
#Column(name="username")
private String Username;
#Column(name="password")
private String Password;
#Column(name="email")
private String Email;
#Column(name="phone")
private String Phone;
#Column(name="rating")
private Integer Rating;
#Column(name="skill")
private Integer Skill;
#Column(name="description")
private String Description;
public String getId() {
return Id;
}
public void setId(String id) {
Id = id;
}
public String getUsername() {
return Username;
}
public void setUsername(String username) {
Username = username;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public String getEmail() {
return Email;
}
public void setEmail(String email) {
Email = email;
}
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public Integer getRating() {
return Rating;
}
public void setRating(Integer rating) {
Rating = rating;
}
public Integer getSkill() {
return Skill;
}
public void setSkill(Integer skill) {
Skill = skill;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}
And this is how I invoke the save() method
package com.chuchurest.proj.Service;
import com.chuchurest.proj.DAO.UserInfoDAO;
import com.chuchurest.proj.Entity.AllUserInfo;
import com.chuchurest.proj.Repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
* Created by slimshady23 on 6/24/2017 AD.
*/
#Service
public class AppService {
#Autowired
private UserRepository userRepository;
public void PerformRegister(AllUserInfo userinfo)
{
userRepository.save(userinfo);
}
}
And here is the Application.properties
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/AllDatabase
spring.datasource.username=root
spring.datasource.password= ******
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
spring.jpa.show-sql= true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
Note the dot, the difference between schema.tablename and tablename alias
The AllUserInfo_f0 is an alias for AllUserInfo. It's used in Hibernate by default for supporting query relations on the same table multiple times. It doesn't break your sql.