When I post the data that time getting this error
Cannot invoke "com.helpmydesk.Repo.UserRepo.save(Object)" because "this.userRepo" is null
at com.helpmydesk.InterFaceAndService.ServiceClass.execute(ServiceClass.java:17) ~[classes/:na]
at com.helpmydesk.ControllerClass.execute(ControllerClass.java:27) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
Main Class
#EnableJpaRepositories("package com.helpmydesk.Repo.UserRepo")
#SpringBootApplication
public class HelpmydeskApplication {
public static void main(String[] args) {
SpringApplication.run(HelpmydeskApplication.class, args);
}
}
Controller Class
#Controller
public class ControllerClass {
#Autowired
private InterfaceClass interfaceClass;
public ControllerClass(InterfaceClass interfaceClass) {
this.interfaceClass = interfaceClass;
}
#PostMapping("/doregister")
public User execute(#RequestBody User user) {
return this.interfaceClass.execute(user);
}
#RequestMapping("/")
public String home() {
return "home";
}
#RequestMapping("/singup")
public String singup() {
return "singup";
}
}
Repository Class
#Repository
public interface UserRepo extends CrudRepository<User, Integer> {
}
interface Class
public interface InterfaceClass {
public User execute(User user);
}
Service Class
#Service
public class ServiceClass implements InterfaceClass {
private UserRepo userRepo;
public User execute(User user) {
this.userRepo.save(user);
return user;
}
}
User Class
#org.hibernate.annotations.Entity
#Table(name = "USER")
public class User {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private int id;
private String name;
#Column(unique = true)
private String email;
private String password;
private String role;
private boolean enabled;
private String imageUrl;
#Column(length = 500)
private String about;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "user")
private java.util.List<Blog> blogs = new ArrayList<>();
public User() {
super();
// TODO Auto-generated constructor stub
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
#Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", email=" + email + ", password=" + password + ", role=" + role
+ ", enabled=" + enabled + ", imageUrl=" + imageUrl + ", about=" + about + "]";
}
}
enter image description here
You don't have #Autowired on your UserRepo variable. You can add it; the better fix is to eliminate field injection and use an ordinary constructor. Spring will provide all of the necessary dependencies when it calls the constructor, it makes testing much easier, and it prevents problems of this sort.
you should add #Autowired in your service class before ligne UserRepo userRepo
because userRepo must be injected before using it
Related
Repository
*As I am trying to enter details of user but i am getting bean Exception i don't what i have missed
from repository interface i have implements JPA and i triad with crud as well . I dint mention any controller class yet
public interface UserRepository extends JpaRepository<User,Long> {
public User findByName(String username);
}
UserModel
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String email;
private Date DOB;
private String Address;
public User() {
}
public User(Long id, String username, String email, Date DOB, String address) {
this.id = id;
this.username = username;
this.email = email;
this.DOB = DOB;
Address = address;
}
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 Date getDOB() {
return DOB;
}
public void setDOB(Date DOB) {
this.DOB = DOB;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
}
UserService
Userservice i have given
public interface UserService {
//Creating User
public User CreateUser(User user) throws Exception;
}
ServiceImp
public class UserServiceImp implements UserService {
#Autowired
private UserRepository userData;
//Creating user
#Override
public User CreateUser(User user) throws Exception {
User local=this.userData.findByName(user.getUsername());
if(local!=null)
{
System.out.println("User is already present!!");
throw new Exception("User is already there");
}
else {
local=this.userData.save(user);
}
return local;
}
}
Main Class
This is the main class
#SpringBootApplication
public class UserInformationApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(UserInformationApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("starting Application");
}
}
Changing this
Use for Spring Version 2.x :
import javax.persistence.*;
to
Use for Spring Version 3.x :
import jakarta.persistence.*;
Worked for me
I am developing an REST API application using spring boot and is struck up with the One to Many mapping while using mappedBy property.
I have User class and Usermeata class, a user can have more than one usermeta.
While the program successfully save the foreign while using JoinColumn, I want to know what mistake I am committing while using mappedby.
Here is my code:
User Entity class:
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long userId;
#Column(unique=true)
private String username;
#Column(unique=true)
private String emailId;
private String password;
private String firstName;
private String lastName;
private String phoneNo;
#OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL,mappedBy="user")
// #JoinColumn(name="user_id")
private List<UserMeta> userMetaList=new ArrayList();
public List<UserMeta> getUserMetaList() {
return userMetaList;
}
public void setUserMetaList(List<UserMeta> userMetaList) {
this.userMetaList = userMetaList;
}
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 getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
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 getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
}
UserMeta class:
#Entity
public class UserMeta {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long userMetaId;
#ManyToOne
#JoinColumn(name="user_id")
private User user;
private String _key;
private String _value;
public Long getUserMetaId() {
return userMetaId;
}
public void setUserMetaId(Long userMetaId) {
this.userMetaId = userMetaId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String get_key() {
return _key;
}
public void set_key(String _key) {
this._key = _key;
}
public String get_value() {
return _value;
}
public void set_value(String _value) {
this._value = _value;
}
}
UserService.class
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public User getUser(Long userId) {
return userRepository.getOne(userId);
}
public List<User> getAllUser() {
return userRepository.findAll();
}
public User addUser(User user) {
return userRepository.save(user);
}
public void removeUser(User user) {
userRepository.delete(user);
}
public void updateUser(User user) {
userRepository.save(user);
}
}
POST request:
{
"username":"myusername",
"emailId":"myemailid#gmail.com1",
"password":"2323#123",
"firstName":"myfname",
"lastName":"mlname",
"phoneNo":"000000",
"userMetaList":[
{
"_key":"api_key",
"_value":"api_key_value"
},
{
"_key":"prop1",
"_value":"val1"
}
]
}
Now the tables are created and updated with the values, however the column user_id in the table usermeta is always null..
I have mapping with class admin and class role I want to show the data od admin class in Json format but I have error Http 500 because this is a mapping between class admin and role how can I do this?
this is my class Admin
#Entity
public class Admin implements Serializable {
#Id
#GeneratedValue
private int idAdmin;
private String email;
private String cin;
private String nom;
private String prenom;
private String loginAdmin;
private String adresse;
private Long tele;
private String motPasse;
private boolean actived;
#ManyToOne
#JoinColumn(name = "idRole")
private Role role;
public Admin() {
super();
}
public int getIdAdmin() {
return idAdmin;
}
public void setIdAdmin(int idAdmin) {
this.idAdmin = idAdmin;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMotPasse() {
return motPasse;
}
public void setMotPasse(String motPasse) {
this.motPasse = motPasse;
}
public boolean isActived() {
return actived;
}
public void setActived(boolean actived) {
this.actived = actived;
}
public String getCin() {
return cin;
}
public void setCin(String cin) {
this.cin = cin;
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public String getLoginAdmin() {
return loginAdmin;
}
public void setLoginAdmin(String loginAdmin) {
this.loginAdmin = loginAdmin;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public Long getTele() {
return tele;
}
public void setTele(Long tele) {
this.tele = tele;
}
}
And this is my role class
#Entity
public class Role implements Serializable {
#Id
#GeneratedValue
private Long idRole;
private String roleName;
#OneToMany(mappedBy = "role")
private List<Admin> admin;
public Role() {
super();
}
public Long getIdRole() {
return idRole;
}
public void setIdRole(Long idRole) {
this.idRole = idRole;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public void setAdmin(List<Admin> admin) {
this.admin = admin;
}
public List<Admin> getAdmin() {
return admin;
}
}
And this is my function in controller to show the data in json format
#RequestMapping(value =" /jsonPosts", method = RequestMethod.GET,produces =
"application/json")
#ResponseBody
public List<Admin> generateJSONPosts() {
return adminService.selectAll();
}
The problem is the mapping between role and admin
I have one REST Call as
List<User> userList = (List<User>) iplUtil.getResult(user, mongoGetURL);
System.out.println("userList === "+userList);
output as
userList = [{_id={$oid=571903dae4b085317593a0d3}, nickName=aa, email=aa, password=aa, userId=1}]
No complile time error..
but this line failing in runtime
User u =userList.get(0);
getting exception at this line as
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.ipl.model.User
and model as
package com.ipl.model;
import java.io.Serializable;
import java.util.Map;
#SuppressWarnings("serial")
public class User implements Serializable {
private Map<String, String> _id;
private String nickName;
private String email;
private String password;
private int userId;
public User(String nickName,String password) {
this.nickName=nickName;
this.password=password;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User() {
// TODO Auto-generated constructor stub
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public Map<String, String> get_id() {
return _id;
}
public void set_id(Map<String, String> _id) {
this._id = _id;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public String toString() {
return "User [_id=" + _id + ", nickName=" + nickName + ", email=" + email + ", password=" + password
+ ", userId=" + userId + "]";
}
}
Im not getting any complie time error..why its failing in runtime
I' currently trying Bean Validation by injecting Validator in a CDI-Bean.
That's why I've written a servlet which injects the validator property. The problem is that im getting wrong results. For example, it says that the name and the surname properties aren't allowed to be null although I've set them with regular name and surnames.
Did I do something wrong?
Here is my Servlet:
#WebServlet
public class BeanValidationServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Inject
private Validator validator;
#Inject
private WorkEmployee workEmployee;
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter writer = response.getWriter();
workEmployee.getAdresse().setPostalCode("8888");
workEmployee.getAdresse().setStreet("Washington Street");
workEmployee.getAdresse().setStreetNumber(98);
workEmployee.getAdresse().setHome("Philadeplphia");
workEmployee.setEmployeeId(12);
workEmployee.setName("John");
workEmployee.setSurname("Doeuuu");
writer.print("<h1> Surname:" + workEmployee.getSurname() + "<h1>");
Set<ConstraintViolation<WorkEmployee>> constraintViolations = validator
.validate(workEmployee);
for (ConstraintViolation<WorkEmployee> violation : constraintViolations) {
writer.print("<h1>" + violation.getPropertyPath() + ": "
+ violation.getMessage() + "<h1>");
writer.print("<h1>" + violation.getRootBean() + "<h1>");
writer.print("<h1>-------------------------------<h1>");
}
Set<ConstraintViolation<Adress>> constraintViolations2 = validator
.validate(workEmployee.getAdresse());
for (ConstraintViolation<Adress> violation : constraintViolations2) {
writer.print("<h1>" + violation.getPropertyPath() + ": "
+ violation.getMessage() + "<h1>");
writer.print("<h1>" + violation.getRootBean() + "<h1>");
writer.print("<h1>-------------------------------<h1>");
}
}
}
And that are my CDI-Beans:
The Worker-class:
#RequestScoped
public class Worker implements WorkEmployee{
#NotNull
private String name;
#NotNull
#Size(min=5,max=15)
#Pattern(regexp="Doe")
private String surname;
#Min(5)
#Max(12)
private int employeeId;
#Inject
#Valid
private Adress adresse;
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name = name;
}
#Override
public String getSurname() {
return surname;
}
#Override
public void setSurname(String surname) {
this.surname = surname;
}
#Override
public int getEmployeeId() {
return employeeId;
}
#Override
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
#Override
public Adress getAdresse() {
return adresse;
}
#Override
public void setAdresse(Adress adresse) {
this.adresse = adresse;
}
}
The Adress-Class:
#RequestScoped
public class Adress {
#Pattern(regexp="^47269$")
private String postalCode;
#NotNull
private String street;
#NotNull
#Min(15)
#Max(99)
private int streetNumber;
#NotNull
#Size(max=25)
private String home;
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public int getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(int streetNumber) {
this.streetNumber = streetNumber;
}
public String getHome() {
return home;
}
public void setHome(String home) {
this.home = home;
}
}