i trying to validate my Model class, which is named user.java, i trying to validate the column to prevent it not empty and the email is should be email format, and i use #RepositoryRestController to create my CRUD api, but how do i do this properly?
here is my user.java :
package com.mechadevapi.mechadev.Models;
import java.util.Date;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import org.springframework.data.annotation.Id;
public class User {
#Id
public String Id;
#NotBlank(message = "is empty")
public String username;
#NotBlank(message = "is empty")
#Email(message = "should be email")
public String email;
#NotBlank(message = "is empty")
public String firstname;
public String lastname;
#NotBlank(message = "is empty")
public String password;
#NotBlank(message = "is empty")
public String level;
#NotBlank(message = "is empty")
public Boolean activation;
public Date entry_time;
public Date last_login;
public String getId() {
return Id;
}
public void setId(String id) {
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 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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getLevel() {
return level;
}
public void setLevel(String level) {
this.level = level;
}
public Boolean getActivation() {
return activation;
}
public void setActivation(Boolean activation) {
this.activation = activation;
}
public Date getEntry_time() {
return entry_time;
}
public void setEntry_time() {
Date entry_time = new Date();
this.entry_time = entry_time;
}
public Date getLast_login() {
return last_login;
}
public void setLast_login() {
Date last_login = new Date();
this.last_login = last_login;
}
}
and here is my repository, UserRepository.java :
package com.mechadevapi.mechadev.Repository;
import javax.validation.Valid;
import com.mechadevapi.mechadev.Models.*;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
#RepositoryRestResource(collectionResourceRel = "user", path = "user")
#Valid
public interface UserRepository extends MongoRepository<User, String> {
}
when i trying to post the data using postman, which is looked like this :
{
"username" : "admin",
"email" : 123,
"firstname" : "ad",
"lastname" : "min",
"password" : "123456",
"level" : "administrator",
"activation" : true
}
the data still saved, it's like the javax.validation anotation is not working, how do i validate this properly?
Related
This will be quite a bit of code as I don't know what will be important. I was trying to recreated the basic UI Alejandro made in my tutorial session with him a few months ago, substituting a table in my database for the one he used. The errors I'm getting all seem related to overriding Vaadin Flow functions. I know that replaces the behavior of the Super method. IntelliJ opens the relevant Super method when I click on the errors, which I'm assuming it wants me to edit to solve the problem, but I have no idea how to do that.
I was going to paste a link to the code but the forum told me to just place it here.
Customer.java
package com.dbproject.storeui;
import java.time.LocalDate;
public class Customer {
private Long id;
private String lastname;
private String firstname;
private String email;
private String password;
private String phone;
private String street;
private String city;
private String st;
private int zip;
private LocalDate dob;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
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 getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getSt() {
return st;
}
public void setSt(String st) {
this.st = st;
}
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
public LocalDate getDob() {
return dob;
}
public void setDob(LocalDate dob) {
this.dob = dob;
}
}
CustomerRepository.java
package com.dbproject.storeui;
import org.apache.ibatis.annotations.*;
import java.util.List;
#Mapper
public interface CustomerMapper {
#Select("SELECT * FROM customer ORDER BY id")
List<Customer> findAll();
#Update("UPDATE customer" +
"SET lastname=#{lastname}, firstname=#{firstname}, email=#{email}, password=#{password}, phone=#{phone}, street=#{street}, city=#{city}, st=${st}, zip=#{zip}, dob=#{dob}" +
"WHERE id=#{id}")
void update(Customer customer);
#Insert("INSERT INTO customer(lastname, firstname, email, password, phone, street, city, st, zip, dob) VALUES(#{lastname}, #{firstname}, #{email}, #{password}, #{phone}, #{street}, #{city}, #{st}, #{zip}, #{dob})")
#Options(useGeneratedKeys = true, keyProperty = "id")
void create(Customer customer);
}
CustomerView.java (the UI class)
package com.dbproject.storeui;
import com.vaadin.flow.component.Composite;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.grid.Grid;
import com.vaadin.flow.component.icon.VaadinIcon;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;
#Route("")
public class CustomerView extends Composite<VerticalLayout> {
private final CustomerMapper customerMapper;
private Grid<Customer> grid = new Grid<>();
private TextField lastname = new TextField("Last Name");
private TextField firstname = new TextField("First Name");
private Button save = new Button("Save", VaadinIcon.CHECK.create());
private Button create = new Button("New", VaadinIcon.PLUS.create());
private VerticalLayout form = new VerticalLayout(lastname, firstname, save);
private Binder<Customer> binder = new Binder<>(Customer.class);
private Customer customer;
public CustomerView(CustomerMapper customerMapper) {
this.customerMapper = customerMapper;
grid.addColumn(Customer::getLastname).setHeader("Last Name");
grid.addColumn(Customer::getFirstname).setHeader("First Name");
grid.addSelectionListener(event -> setCustomer(grid.asSingleSelect().getValue()));
updateGrid();
save.addClickListener(event -> saveClicked());
create.addClickListener(event -> createClicked());
getContent().add(grid, create, form);
binder.bindInstanceFields(this);
binder.setBean(null);
}
private void createClicked() {
grid.asSingleSelect().clear();
setCustomer(new Customer());
}
private void saveClicked() {
binder.readBean(customer);
if (customer.getId() == null) {
customerMapper.create(customer);
} else {
customerMapper.update(customer);
}
updateGrid();
Notification.show("Saved!");
}
private void setCustomer(Customer customer) {
this.customer = customer;
form.setEnabled(customer != null);
binder.setBean(customer);
}
private void updateGrid() {
grid.setItems(customerMapper.findAll());
}
}
I am having trouble understanding why my userRepository is returning null even when there is a record like it in my table. I tried doing it with my demo codes and it works but when I try doing it with user Authentication it does not work.
Security Services
#Path("/securityservice")
public class SecurityServices {
private UserRepository userRepo;
// http://localhost:8990/login/securityservice/security
#GET
#Path("security")
#Produces(MediaType.APPLICATION_JSON)
public Response getOrderById(#QueryParam("orderId") int orderID,
#HeaderParam("Authorization") String authString) throws JSONException {
JSONObject json = new JSONObject();
if (isUserAuthenticated(authString)) {
json.put("INFO", "Authorized User!");
return Response.status(200)
.entity(json.toString())
.type(MediaType.APPLICATION_JSON)
.build();
} else {
json.put("ERROR", "Unauthorized User!");
return Response.status(403)
.entity(json.toString())
.type(MediaType.APPLICATION_JSON)
.build();
}
}
private boolean isUserAuthenticated(String authString) {
//authString = Basic 3hfjdksiwoeriounf
String[] authParts = authString.split("\\s+");
//authParts[0] = Basic
//authParts[1] = 3hfjdksiwoeriounf
String authInfo = authParts[1];
byte[] bytes = Base64.getDecoder().decode(authInfo);
String decodedAuth = new String(bytes);
// decodedAuth = dj:1234
String[] credentials = decodedAuth.split(":");
//credentials[0]=dj
//credentials[1]=1234
System.out.println("HELLO"+credentials[0]);
System.out.println("HELLO"+credentials[1]);
User user = userRepo.findByUsername(credentials[0]); //this line returns null
if (user != null) {
return true;
} else {
return false;
}
}
User class (Getters and setters for the JPA Repo)
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name="firstname")
private String firstName;
#Column(name="lastname")
private String lastName;
private String password;
private String username;
#Column(name="accesstype")
private String accessType;
public User() {
super();
}
public User(String firstName, String lastName, String password,
String username, String accessType) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.username = username;
this.accessType = accessType;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAccessType() {
return accessType;
}
public void setAccessType(String accessType) {
this.accessType = accessType;
}
}
I am implementing a sample Spring MVC Form with Form Validation. I have a complex type Address as bean property for Student form bean. And I have added form validation #NotEmpty for Address bean properties. But the same is not reflecting in the UI. But form validation works for other primitive types of Student form bean.
So, Validation works perfectly for Student form bean but not for nested complex types like Address within Student form bean.
I am trying understand the reason and a fix.
Spring version 4.0+.
Hibernate Validator api:5.2.4
Student POJO:
package com.xyz.form.beans;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.Past;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
import com.xyz.validators.DateNotEmpty;
import com.xyz.validators.ListNotEmpty;
public class Student {
#Size(min = 2, max = 30)
private String firstName;
#Size(min = 2, max = 30)
private String lastName;
#NotEmpty
private String gender;
#DateNotEmpty
#Past
private Date DOB;
private String email;
private String mobileNumber;
#ListNotEmpty
private List<String> courses;
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getDOB() {
return DOB;
}
public void setDOB(Date dOB) {
DOB = dOB;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobileNumber() {
return mobileNumber;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public List<String> getCourses() {
return courses;
}
public void setCourses(List<String> courses) {
this.courses = courses;
}
}
Address POJO:
package com.xyz.form.beans;
import org.hibernate.validator.constraints.NotEmpty;
import com.xyz.validators.LongNotEmpty;
public class Address {
#NotEmpty
private String houseNo;
#NotEmpty
private String street;
#NotEmpty
private String area;
#NotEmpty
private String city;
#LongNotEmpty
private Long pin;
public String getHouseNo() {
return houseNo;
}
public void setHouseNo(String houseNo) {
this.houseNo = houseNo;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Long getPin() {
return pin;
}
public void setPin(Long pin) {
this.pin = pin;
}
}
Student Controller:
#RequestMapping(value = "/newStudentDetails.do", method = RequestMethod.POST)
public ModelAndView newStudentDetails(
#Valid #ModelAttribute("student") com.xyz.form.beans.Student studentFormBean,
BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return new ModelAndView("newStudentPage");
}
Student studentDto = new Student();
studentDto.setFirstName(studentFormBean.getFirstName());
studentDto.setLastName(studentFormBean.getLastName());
studentDto.setGender(studentFormBean.getGender());
studentDto.setDOB(new Date(studentFormBean.getDOB().getTime()));
studentDto.setEmail(studentFormBean.getEmail());
studentDto.setMobileNumber(studentFormBean.getMobileNumber());
StringBuilder sb = new StringBuilder();
sb.append(studentFormBean.getAddress().getHouseNo() + ", ");
sb.append(studentFormBean.getAddress().getStreet() + ", ");
sb.append(studentFormBean.getAddress().getArea() + ", ");
sb.append(studentFormBean.getAddress().getCity() + "-");
sb.append(studentFormBean.getAddress().getPin());
studentDto.setAddress(sb.toString());
studentDto.setCourses(studentFormBean.getCourses());
studentDao.createStudent(studentDto);
ModelAndView mav = new ModelAndView("newStudentSuccess");
return mav;
}
Thanks,
Viswanath
You need to annotate your complex types with #Valid.
This is the reference (which references here)
Hi lets try #ModelAttribute("student") #Valid com.xyz.form.beans.Student studentFormBean in place of #Valid #ModelAttribute("student")
For nested complex types, you have to activate the direct field access. Just like below:
#org.springframework.web.bind.annotation.ControllerAdvice
public class ControllerAdvice {
#InitBinder
public void initBinder(WebDataBinder webDataBinder) {
webDataBinder.initDirectFieldAccess();
}
I have a problem with Hibernate. Im struggling with this since yesterday, it seems very easy but I have no idea why it is not working...
I have entity Login.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class Login {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false, unique = true)
String username;
#Column(nullable = false)
String password;
public Login(){
}
public Login(String username, String password){
this.username = username;
this.password = password;
}
public Login(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.username = (String) jsonObject.get("username");
this.password = (String) jsonObject.get("password");
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("username", this.username);
jsonObject.put("password", this.password);
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
}
And entity TourOffice.java:
package offersmanager.model.entity;
import org.json.JSONObject;
import javax.persistence.*;
#Entity
public class TourOffice {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false)
String officeName;
#Column(nullable = false)
String eMail;
#Column(nullable = false)
String phoneNumber;
#Column(nullable = false)
String city;
#Column(nullable = false)
String zipCode;
#Column(nullable = false)
String address;
#OneToOne(cascade = {CascadeType.ALL})
#JoinColumn(name = "login_id")
Login login;
public TourOffice(){
}
public TourOffice(String officeName, String eMail, String phoneNumber, String city, String zipCode, String address) {
this.officeName = officeName;
this.eMail = eMail;
this.phoneNumber = phoneNumber;
this.city = city;
this.zipCode = zipCode;
this.address = address;
}
public TourOffice(JSONObject jsonObject) {
this.id = (Integer) jsonObject.get("id");
this.officeName = (String) jsonObject.get("officeName");
this.eMail = (String) jsonObject.get("eMail");
this.phoneNumber = (String) jsonObject.get("phoneNumber");
this.city = (String) jsonObject.get("city");
this.zipCode = (String) jsonObject.get("zipCode");
this.address = (String) jsonObject.get("address");
this.login = (new Login((JSONObject) jsonObject.get("login")));
}
public JSONObject toJsonObject() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("id", this.id);
jsonObject.put("officeName", this.officeName);
jsonObject.put("eMail", this.eMail);
jsonObject.put("phoneNumber", this.phoneNumber);
jsonObject.put("city", this.city);
jsonObject.put("zipCode", this.zipCode);
jsonObject.put("address", this.address);
jsonObject.put("login", this.login == null? null : login.toJsonObject());
return jsonObject;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getOfficeName() {
return officeName;
}
public void setOfficeName(String officeName) {
this.officeName = officeName;
}
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 getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Login getLogin() {
return login;
}
public void setLogin(Login login) {
this.login = login;
}
}
These entities are connected with #OneToOne relation.
What I'm trying to do is to find the name of my office (officeName) with field of Login class (username).
This is my function in TourOfficeDAO.java:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}
It goes through TourOfficeService to my rest controller where this method is invoked. But it doesn't matter cause exeception is thrown in DAO:
could not resolve property: login.username of:
offersmanager.model.entity.TourOffice; nested exception is
org.hibernate.QueryException: could not resolve property:
login.username of: offersmanager.model.entity.TourOffice
It can't find "login.username" and have no idea why... everything seems good.
I looked for similiar topics but I haven't still managed to make this works. Any help would be appreciated.
EDIT 1:
This is my abstract class DAO.java where is the function createCriteria()
public abstract class DAO<MODEL> implements Serializable {
public abstract Class<MODEL> getEntityClass();
#Autowired
protected SessionFactory sessionFactory;
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
protected Query createQuery(String query){
return getSession().createQuery(query);
}
protected SQLQuery createSQLQuery(String query){
return getSession().createSQLQuery(query);
}
protected Criteria createCriteria(){
return getSession().createCriteria(getEntityClass());
}
#SuppressWarnings("unchecked")
public MODEL findById(Integer id) {
return (MODEL) getSession().get(getEntityClass(), id);
}
public void save(MODEL entity) {
getSession().save(entity);
getSession().flush();
}
public void update(MODEL entity) {
getSession().update(entity);
getSession().flush();
}
public void saveOrUpdate(MODEL entity) {
getSession().saveOrUpdate(entity);
getSession().flush();
}
public void delete(MODEL entity) {
getSession().delete(entity);
getSession().flush();
}
public List<MODEL> list(){
Criteria criteria = createCriteria();
#SuppressWarnings("unchecked")
List<MODEL> list = criteria.list();
return list;
}
}
I think you need first to create an alias like that:
public TourOffice findOfficeNameByLogin(String username) {
Criteria name = createCriteria();
name.createAlias("login", "login");
name.add(Restrictions.eq("login.username", username));
return (TourOffice) name.uniqueResult();
}
I can't seem to get my form to bind to the checkboxes control. I read many posts on here and tried a few techniques but no luck. Maybe a fresh set of eyes will help.
my controller:
public String editAccount(#RequestParam("id") String id, Model model) {
model.addAttribute("account", accountService.getAccount(id));
model.addAttribute("allRoles", roleService.getRoles());
return EDIT_ACCOUNT;
}
my jsp:
<form:form action="" modelAttribute="account">
<form:checkboxes items="${allRoles}" path="roles" itemLabel="name" itemValue="id" delimiter="<br/>"/>
</form>
the generated html:
<span><input id="roles1" name="roles" type="checkbox" value="1"/><label for="roles1">User</label></span><span><br/><input id="roles2" name="roles" type="checkbox" value="2"/><label for="roles2">Admin</label></span><span><br/><input id="roles3" name="roles" type="checkbox" value="3"/><label for="roles3">SuperAdmin</label></span<input type="hidden" name="_roles" value="on"/>
I used a second for each loop (not shown) to make sure that the model object contained the roles. It does, yet none of the checkboxes are checked and when I submit the roles object is always empty. Can someone please tell me what I'm missing?
Thanks
EDIT
Sorry just realized it might be helpful to see the account and role objects:
public class Account {
private String username, firstName, lastName, email;
private List<Role> roles;
#NotNull
#Size(min = 1, max = 50)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#NotNull
#Size(min = 1, max = 50)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#NotNull
#Size(min = 1, max = 50)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#NotNull
#Size(min = 6, max = 50)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
public class Role {
private int id;
private String name;
public Role() {}
public Role(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#NotNull
#Size(min = 1, max = 50)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
EDIT #2
Controller Post Method
#RequestMapping(value = "edit", method = RequestMethod.POST)
public String updateAccount(#RequestParam("id") String id, #ModelAttribute("account") #Valid AccountEditForm form, BindingResult result) {
System.out.println("FORM VALUES AFTER: " + form);
return (result.hasErrors() ? EDIT_ACCOUNT : ACCOUNT_REDIRECT);
}
AccountEditForm is the form backing object. When I do a GET I grab an Account object and pass the values into an AccountEditForm before displaying the screen. I will attach the AccountEditForm just for clarity. It is very similiar to the account object. I just happened to seperate my form objects from my model objects.
public class AccountEditForm {
private String username, firstName, lastName, email;
private List<Role> roles = new ArrayList<Role>();
#NotNull
#Size(min = 1, max = 50)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#NotNull
#Size(min = 1, max = 50)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#NotNull
#Size(min = 1, max = 50)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#NotNull
#Size(min = 6, max = 50)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
EDIT #3 Role Property Editor
public class RolePropertyEditor extends PropertyEditorSupport {
private Map<Integer, Role> roleMap = new HashMap<Integer, Role>();
public RolePropertyEditor(List<Role> roleList) {
for (Role r : roleList) roleMap.put(r.getId(), r);
}
public void setAsText(String incomingId) {
Role role = roleMap.get(incomingId);
System.out.println("PROPERTY EDITOR ROLE " + role);
setValue(role);
}
public String getAsText() {
System.out.println("PROPERTY EDITOR ID " + ((Role)getValue()).getId());
return String.valueOf(((Role)getValue()).getId());
}
}
Defined in my controller like:
#InitBinder
public void initBinder(WebDataBinder binder) {
binder.setAllowedFields(new String[] {
"username", "password", "confirmPassword", "firstName", "lastName", "email", "acceptTerms", "currentPassword"
});
binder.registerCustomEditor(Role.class, new RolePropertyEditor(roleService.getRoles()));
}
EDIT #4 NEW ProeprtyEditor
public class SecurityRolePropertyEditor extends PropertyEditorSupport {
private RoleService roleService;
public SecurityRolePropertyEditor(RoleService roleService) {
this.roleService = roleService;
}
public void setAsText(final String name) {
Role role = roleService.getRoleByName(name);
setValue(role);
}
}
Add an equals method to your Roles entity.
see this answer (Spring MVC Pre Populate Checkboxes): of a similar question for more details.
It seems you are missing implementation equals and hashCode method on your entities.