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

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.

Related

Return key value of a JSON request in Spring

I'm trying to create a route to perform a GET Request to /winner to show the restaurants that had the count of 3 votes in the JSON, but every time I do the GET, it returns the value of null instead of the value I would like.
I was expecting something like that:
{
"id": 1,
"restaurant": "Burger King",
"address": "Av. Ipiranga, 1600",
"website": "https://www.burgerking.com.br/",
"description": "Rede de fast-food famosa com hambúrgueres grelhados, batata frita e milk-shakes.",
"count": 3
}
Instead that, I'm just getting an empty JSON with the null value.
Here are the classes I'm using:
Restaurant.java
package com.dbserver.restaurantes.entities;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "db_restaurants")
public class Restaurant {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String restaurant;
private String address;
private String website;
private String description;
private Integer count;
#OneToMany(mappedBy = "id.restaurant")
private Set<Vote> votes = new HashSet<>();
public Restaurant() {
}
public Restaurant(Long id, String restaurant, String address, String website, String description, Integer count) {
this.id = id;
this.restaurant = restaurant;
this.address = address;
this.website = website;
this.description = description;
this.count = count;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Set<Vote> getVotes() {
return votes;
}
}
RestaurantDTO.java
package com.dbserver.restaurantes.dto;
import com.dbserver.restaurantes.entities.Restaurant;
public class RestaurantDTO {
private Long id;
private String restaurant;
private String address;
private String website;
private String description;
private Integer count;
public RestaurantDTO() {
}
public RestaurantDTO(Long id, String restaurant, String address, String website, String description, Integer count) {
this.id = id;
this.restaurant = restaurant;
this.address = address;
this.website = website;
this.description = description;
this.count = count;
}
public RestaurantDTO(Restaurant restaurantDTO) {
id = restaurantDTO.getId();
restaurant = restaurantDTO.getRestaurant();
address = restaurantDTO.getAddress();
website = restaurantDTO.getWebsite();
description = restaurantDTO.getDescription();
count = restaurantDTO.getCount();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRestaurant() {
return restaurant;
}
public void setRestaurant(String restaurant) {
this.restaurant = restaurant;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}
RestaurantServices.java
package com.dbserver.restaurantes.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dbserver.restaurantes.dto.RestaurantDTO;
import com.dbserver.restaurantes.dto.VoteDTO;
import com.dbserver.restaurantes.entities.Restaurant;
import com.dbserver.restaurantes.repositories.RestaurantRepository;
#Service
public class RestaurantServices {
#Autowired
private RestaurantRepository repository;
#Transactional(readOnly = true)
public Page<RestaurantDTO> findAll(Pageable pageable) {
Page<Restaurant> result = repository.findAll(pageable);
Page<RestaurantDTO> page = result.map(x -> new RestaurantDTO(x));
return page;
}
#Transactional(readOnly = true)
public RestaurantDTO findById(Long id) {
Restaurant result = repository.findById(id).get();
RestaurantDTO dto = new RestaurantDTO(result);
return dto;
}
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = new ArrayList<>();
for (Restaurant restaurant: restaurants) {
if(restaurant.getCount().equals(3)) {
return restaurant;
}
}
return null;
}
#Transactional
public Restaurant addRestaurant(Restaurant newRestaurant) {
return repository.saveAndFlush(newRestaurant);
}
}
RestaurantController.java
package com.dbserver.restaurantes.controllers;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
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 com.dbserver.restaurantes.dto.RestaurantDTO;
import com.dbserver.restaurantes.entities.Restaurant;
import com.dbserver.restaurantes.services.RestaurantServices;
#RestController
#RequestMapping(value = "/restaurants")
public class RestaurantController {
#Autowired
private RestaurantServices service;
#GetMapping
public Page<RestaurantDTO> findAll(Pageable pageable) {
return service.findAll(pageable);
}
#GetMapping(value = "/{id}")
public RestaurantDTO findById(#PathVariable Long id) {
return service.findById(id);
}
#SuppressWarnings("unchecked")
#GetMapping(value = "/winner")
public List<RestaurantDTO> findWinner(Integer count) {
return (List<RestaurantDTO>) service.findWinner(3);
};
#PostMapping
public Restaurant addRestaurant(#RequestBody Restaurant newRestaurant) {
return service.addRestaurant(newRestaurant);
}
}
you didn't access dao in the method findWinner.
restaurants instance has just created without accessing dao.
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = new ArrayList<>();
for (Restaurant restaurant: restaurants) {
if(restaurant.getCount().equals(3)) {
return restaurant;
}
}
return null;
}
because in the find winner method you have initialized restaurants with an empty array list.
It should be like this.
#Transactional(readOnly = true)
public Restaurant findWinner(Integer count) {
List<Restaurant> restaurants = repository.findAll();
for (Restaurant restaurant: restaurants) {
if(restaurant.getCount().equals(3)) {
return restaurant;
}
}
return null;
}

How to resolve the problem of foreign key of being zero all time when data inserted to tables using spring boot?

User.java
package com.spring.demo.model;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
#Entity
#Table(name="user")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="user_id")
private int id;
private String fName;
private String lName;
#Column(unique=true,nullable=true)
private String email;
#Column(unique=true,nullable=true)
private long mobile;
private Date dob;
#Lob
private byte[] image;
#Transient
private String base64Image;
#OneToOne(cascade=CascadeType.ALL,fetch =FetchType.EAGER)
#JoinColumn(name="userCredential_id")
private UserCredential userCredential;
#OneToOne(cascade=CascadeType.ALL,fetch =FetchType.EAGER)
#JoinColumn(name="add_id")
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getfName() {
return fName;
}
public void setfName(String fName) {
this.fName = fName;
}
public String getlName() {
return lName;
}
public void setlName(String lName) {
this.lName = lName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public long getMobile() {
return mobile;
}
public void setMobile(long mobile) {
this.mobile = mobile;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public UserCredential getUserCredential() {
return userCredential;
}
public void setUserCredential(UserCredential userCredential) {
this.userCredential = userCredential;
}
}
UserCredential.java
package com.spring.demo.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="usercredential")
public class UserCredential {
#Id
#Column(name="credential_id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(unique=true,nullable=true)
private String username;
private String password;
private String cnfrmpassword;
#JsonIgnore
#OneToOne(cascade=CascadeType.ALL,fetch =FetchType.EAGER)
#JoinColumn(name="user_id",nullable=true)
private User user;
public UserCredential() {
super();
// TODO Auto-generated constructor stub
}
public UserCredential(int id, String username, String password, String cnfrmpassword, User user) {
super();
this.id = id;
this.username = username;
this.password = password;
this.cnfrmpassword = cnfrmpassword;
this.user = user;
}
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 getCnfrmpassword() {
return cnfrmpassword;
}
public void setCnfrmpassword(String cnfrmpassword) {
this.cnfrmpassword = cnfrmpassword;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Address.java
package com.spring.demo.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#Table(name="address")
public class Address {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="add_id")
private int id;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="house_no")
private String h_no;
#JsonIgnore
#OneToOne(cascade=CascadeType.ALL,fetch =FetchType.EAGER)
#JoinColumn(name="user_id", nullable=true)
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getH_no() {
return h_no;
}
public void setH_no(String h_no) {
this.h_no = h_no;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
Here we have user as a parent table and (usercredential and address) are child classes in a relationship. When I insert data into tables then every primary key automatically incremented and get the appropriate value while the foreign key (user_id) always remains zero.
https://i.stack.imgur.com/Pivlm.jpg
https://i.stack.imgur.com/fAPth.jpg
https://i.stack.imgur.com/l37mr.jpg
My concern is user_id(foreign key) in child tables should not be null and equals to primary key(user_id) in parent table. Please look for every cascading(delete, update) operation should be implemented well on table.
Further information I am using Json for inserting data into tables.
{
"fName":"sur kumst",
"lName":"adfdf",
"mobile":45106,
"email":"ksusjasd1sd#gmail.com",
"dob":"2012-04-23T18:25:43.511Z",
"address":{
"city":"noida",
"state":"up",
"h_no":"1243"
},
"userCredential":{
"username":"kr0302",
"password":"12345",
"cnfrmpassword":"12345"
}
}
The issue is with the back reference. Hibernate cannot maintain this for you. Say you save your user object. it creates a credential row and generates id. it creates address and id. it updates the cred_id and add_id on the user object and then creates a row for it and generates id and returns that value. at this point you need to add your user object to credential and address and save those again.
It seems you are trying to model two bidirectional relationships:
User <-> UserCredentials and:
User <-> UserAddress.
But what you are really creating the following four relationships:
User -> UserCredentials
User <- UserCredentials
User -> UserAddress
User <- UserAddress
In order to fix this you need to use mappedBy. See this question for reference.

I am trying to insert into database.n getting an error "java.lang.IllegalArgumentException: attempt to create saveOrUpdate event with null entity"

This is my POJO CLASS
package model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="Registration")
public class RegistrationModel {
private int id;
private String firstName;
private String lastName;
private String cellno;
private String city;
private String state;
private String pincode;
#Id
#GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="First_Name")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name="Last_Name")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name="Cell_no")
public String getCellno() {
return cellno;
}
public void setCellno(String cellno) {
this.cellno = cellno;
}
#Column(name="City")
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#Column(name="State")
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
#Column(name="Pincode")
public String getPincode() {
return pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
}
ACTION CLASS
package action;
import java.io.Serializable;
import service.RegistrationService;
import model.RegistrationModel;
import com.opensymphony.xwork2.ActionSupport;
public class RegistrationAction extends ActionSupport
{
private RegistrationModel model;
private RegistrationService registrationService;
public RegistrationModel getModel() {
return model;
}
public void setModel(RegistrationModel model) {
this.model = model;
}
public RegistrationAction() {
registrationService=new RegistrationService();
}
#Override
public String execute() throws Exception {
if(null!=getModel())
{
registrationService.add(getModel());
}
return SUCCESS;
}
public String addRegistrationDetails()
{
System.out.println("pramod");
System.out.println(getModel());
RegistrationModel queryResult=registrationService.add(getModel());
return SUCCESS;
}
}
SERVICE CLASS
package service;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import model.RegistrationModel;
import action.RegistrationAction;
public class RegistrationService {
public RegistrationModel add(RegistrationModel model)
{
SessionFactory sessionFactory=new AnnotationConfiguration().configure().buildSessionFactory();
Session session =sessionFactory.openSession();
session.beginTransaction();
session.beginTransaction();
session.save(model);
session.getTransaction().commit();
return model;
}
}
I'm trying to insert this data into database but getting this error:
java.lang.IllegalArgumentException: attempt to create saveOrUpdate event with null entity.
Doing Struts2 and Hibernate integration
Validate if the model is not null
if(model == null)
throws new IllegalArgumentException("Model is null");
session.save(model);
You should use a nullable id type, so Hibernate knows when you are passing a transitive entity:
private Integer id;

Hibernate Relational one to many Mapping Issue

I have a issue regarding one to many mapping in hibernate 4.x and I am using mysql5.6.
First Let show you my 2 entities,
first user entity,
package com.project.entities;
import java.util.ArrayList;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="UserBookingEntryTable")
public class UserBookingEntryClass {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int uid;
private String ubmobile_no;
private String ubname;
#OneToMany(cascade = {CascadeType.ALL},mappedBy="user")
private Collection<BookingServicesClass> bookings=new ArrayList<BookingServicesClass>();
public Collection<BookingServicesClass> getBookings() {
return bookings;
}
public void setBookings(Collection<BookingServicesClass> bookings) {
this.bookings = bookings;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUbmobile_no() {
return ubmobile_no;
}
public void setUbmobile_no(String ubmobile_no) {
this.ubmobile_no = ubmobile_no;
}
public String getUbname() {
return ubname;
}
public void setUbname(String ubname) {
this.ubname = ubname;
}
}
Second Entity -Booking Class
package com.project.entities;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "BookingServiceTable")
public class BookingServicesClass {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int booking_id;
private String first_name;
private String last_name;
private String mobile;
private String location;
private String booking_address;
private String booking_type;
private String landmark;
private int booking_pincode;
private Date booking_date;
#ManyToOne
#JoinColumn(name="usid")
private UserBookingEntryClass user;
public Integer getBooking_id() {
return booking_id;
}
public void setBooking_id(Integer booking_id) {
this.booking_id = booking_id;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getBooking_address() {
return booking_address;
}
public void setBooking_address(String booking_address) {
this.booking_address = booking_address;
}
public String getLandmark() {
return landmark;
}
public void setLandmark(String landmark) {
this.landmark = landmark;
}
public Integer getBooking_pincode() {
return booking_pincode;
}
public void setBooking_pincode(Integer booking_pincode) {
this.booking_pincode = booking_pincode;
}
public Date getBooking_date() {
return booking_date;
}
public void setBooking_date(Date booking_date) {
this.booking_date = booking_date;
}
public String getBooking_type() {
return booking_type;
}
public void setBooking_type(String booking_type) {
this.booking_type = booking_type;
}
public UserBookingEntryClass getUser() {
return user;
}
public void setUser(UserBookingEntryClass user) {
this.user = user;
}
}
// to add booking from a user:
public String addService(String fname, String lname, String mob,
String ser, String loc, String add, String lm, int pc, String bd) {
String res = "failure";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date convertedCurrentDate = null;
try {
convertedCurrentDate = sdf.parse(bd);
} catch (ParseException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BookingServicesClass bs = new BookingServicesClass();
UserBookingEntryClass ubs = new UserBookingEntryClass();
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
System.out.println("dddd");
try {
**//userid is auto generated**
ubs.setUbmobile_no(mob);
ubs.setUbname((fname + " " + lname));
// bs.setBid(1);
bs.setFirst_name(fname);
bs.setLast_name(lname);
bs.setMobile(mob);
bs.setLocation(loc);
bs.setBooking_type(ser);
bs.setBooking_address(add);
bs.setLandmark(lm);
bs.setBooking_pincode(pc);
bs.setBooking_date(convertedCurrentDate);
bs.setUser(ubs);
session.save(ubs);
session.save(bs);
// Commit the transaction
session.getTransaction().commit();
/*session.close();*/
res = "success";
System.out.println("ajax");
} catch (Exception e) {
System.out.println(e);
session.getTransaction().rollback();
res = "failure";
// success=false;
}
return res;
}
Now the issue is that one user can do more than one booking.
So the code create a foreign key in booking table which is users key who is booking.
but when the one user books more than one booking the Unique constraint Error is given.
So i made the userid auto genrate which is not according to my needs,
becuase if same user books two booking then userid should be same but when i do this it gives me unique constraint error.
Please tell how should I implement it.
Thanks
First thing - id of User should not be auto generated, maybe the mobilenumber which will definitely be unique should be the identifier
Second thing - When you add the booking you will check if the user exists , if it exists add the booking to the user ,otherwise create the user and add the bookings, and then commit the user.
Try these and let me know.
BookingServicesClass booking = new BookingServicesClass ()
if(ubmobile_no!=null) {
UserBookingEntryClass user= session.get(UserBookingEntryClass .class, ubmobile_no);
if (user!= null) {
booking.setUser(user);
user.getBookings().add(booking);
} else {
//do nothing
}
}

Could not determine a type by Hibernate

When I launch my Spring Hibernate App, I get this error :
Error creating bean with name 'manageUserDAO': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory edusef.dao.ManageUserDAO.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SessionFactory' defined in ServletContext resource [/WEB-INF/application-context.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not determine type for: edusef.model.Roles, at table: USER, for columns: [org.hibernate.mapping.Column(roles)]
I'm not a real guru on J2EE and this almost my first advanced app. I don't know what is happening there, here is my User and Roles models :
package edusef.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.CascadeType;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
import javax.persistence.ManyToOne;
import java.util.Date;
#Entity
#Table (name="USER")
public class User {
private int idUser;
private String NomUser;
private String PrenUser;
private String MailUser;
private String AdressUser;
private int PhoneUser;
private Date DateNaissanceUser;
private int AccountStatus;
private String Password;
private String Login;
private char SexeUser;
private String ImagePath;
private int idRole;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="IDUSER", unique = true, nullable = false)
public int getidUser() { return idUser; }
public void setidUser(int iduser) { this.idUser = iduser; }
#Column(name="NOMUSER", nullable = false)
public String getNomUser() { return NomUser; }
public void setNomUser(String nomUser) { this.NomUser = nomUser; }
#Column(name="PRENUSER", nullable = false)
public String getPrenUser() { return PrenUser; }
public void setPrenUser(String prenUser) { this.PrenUser = prenUser; }
#Column(name="MAILUSER", nullable = false)
public String getMailUser() { return MailUser; }
public void setMailUser(String mailUser) { this.MailUser = mailUser; }
#Column(name="ADRESSUSER", nullable = false)
public String getAdressUser() { return AdressUser; }
public void setAdressUser(String adressUser) { this.AdressUser = adressUser; }
#Column(name="PHONEUSER", nullable = false)
public int getPhoneUser() { return PhoneUser; }
public void setPhoneUser(int phoneUser) { this.PhoneUser = phoneUser; }
#Column(name="DATENAISSANCEUSER", nullable = false)
public Date getDateNaissanceUser() { return DateNaissanceUser; }
public void setDateNaissanceUser(Date dateNaissanceUser) { this.DateNaissanceUser = dateNaissanceUser; }
#Column(name="ACCOUNTSTATUS", nullable = false)
public int getAccountStatus() { return AccountStatus; }
public void setAccountStatus(int accountStatus) { this.AccountStatus = accountStatus; }
#Column(name="PASSWORD", nullable = false)
public String getPassword() { return Password; }
public void setPassword(String password) { this.Password = password; }
#Column(name="LOGIN", nullable = false)
public String getLogin() { return Login; }
public void setLogin(String login) { this.Login = login; }
#Column(name="SEXEUSER", nullable = false)
public char getSexeUser() { return SexeUser; }
public void setSexeUser(char sexeUser) { this.SexeUser = sexeUser; }
#Column(name="IMAGEPATH", nullable = true)
public String getImagePath() { return ImagePath; }
public void setImagePath(String imagePath) { this.ImagePath = imagePath; }
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="IDROLE", nullable=false)
public int getidRole() { return idRole; }
public void setidRole(int idRole) { this.idRole = idRole; }
private Roles roles;
public Roles getRoles() {
return roles;
}
public void setRoles(Roles roles) {
this.roles = roles;
}
#Override
public String toString() {
StringBuffer strBuff = new StringBuffer();
strBuff.append("idUser : ").append(getidUser());
strBuff.append(", NomUser : ").append(getNomUser());
strBuff.append(", PrenUser : ").append(getPrenUser());
strBuff.append(", MailUser : ").append(getMailUser());
strBuff.append(", AdressUser : ").append(getAdressUser());
strBuff.append(", PhoneUser : ").append(getPhoneUser());
strBuff.append(", DateNaissanceUser : ").append(getDateNaissanceUser());
strBuff.append(", AccountStatus : ").append(getAccountStatus());
strBuff.append(", Password : ").append(getPassword());
strBuff.append(", Login : ").append(getLogin());
strBuff.append(", SexeUser : ").append(getSexeUser());
strBuff.append(", ImagePath : ").append(getImagePath());
// strBuff.append(", idRole : ").append(getidRole());
return strBuff.toString();
}
}
Roles :
package edusef.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table (name="ROLES")
public class Roles {
private int idRole;
private String Role;
#Id
#Column(name="IDROLE", unique = true, nullable = false)
public int getIdRole() { return idRole; }
public void setIdRole(int idRole) { this.idRole = idRole; }
#Column(name="ROLES", nullable = false)
public String getRole() { return Role; }
public void setRole(String role) { Role = role; }
}
ManageUserDAO :
package edusef.dao;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import edusef.model.User;
import java.util.List;
#Repository
public class ManageUserDAO {
public #interface ComponentScan {
}
#Autowired
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() { return sessionFactory; }
public void setSessionFactory(SessionFactory sessionFactory) {this.sessionFactory = sessionFactory;}
public void addUser(User user) {
getSessionFactory().getCurrentSession().save(user);
}
public void deleteUser(User user) {
getSessionFactory().getCurrentSession().delete(user);
}
public void updateUser(User user) {
getSessionFactory().getCurrentSession().update(user);
}
public User getUserById(int id) {
List list = getSessionFactory().getCurrentSession().createQuery("from User where id=?").setParameter(0, id).list();
return (User)list.get(0);
}
public List<User> getUsers() {
List list = getSessionFactory().getCurrentSession().createQuery("from User").list();
return list;
}
}
RolesDAOImpl :
public class RolesDAOImpl implements RolesDAO {
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
public Roles getRoles(int idRole) {
Roles role = (Roles) getCurrentSession().load(Roles.class, idRole);
return role;
}
}
My Logic is that each User has one Role (ManyToOne) and each role can be used by many users. the User.idRole entity should return the idRole of the User and depending on it we test the user role on Spring Security ..
Any help is welcome ! Thanks
You're trying to map an int with #ManyToOne in your User class. You should be mapping a Role instead.
Remove the getIdRole() and setIdRole() methods from this part, they don't belong there.
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="IDROLE", nullable=false)
public int getidRole() { return idRole; }
public void setidRole(int idRole) { this.idRole = idRole; }
private Roles roles;
public Roles getRoles() {
return roles;
}

Categories

Resources