Spring boot DTO is null at Controller - java

Am new to Spring boot. Am trying to create an endpoint that will add vehicle under manager. I have two entites Vehicle and Manager and corresponding DTO are below. ManagerDTO has reference of VehicleDTO
VehicleDTO
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.EngineType;
import com.Manufacturer;
#JsonDeserialize(builder = VehicleDTO.VehicleDTOBuilder.class)
#JsonInclude(JsonInclude.Include.NON_NULL)
public class VehicleDTO {
private Long vehicleid;
#NotNull(message = "vehcilenumber can not be null!")
#Size(min = 2, max = 14)
private String vehcilenumber;
#NotNull(message = "Engine Type can not be null!")
private EngineType enginetype;
#Min(1)
#Max(5)
private Integer rating;
private Manufacturer manufacturer;
private VehicleDTO(Long id, String vehcilenumber, EngineType enginetype,Integer rating,Manufacturer manufacturer){
this.vehcilenumber=vehcilenumber;
this.enginetype=enginetype;
this.rating=rating;
this.vehicleid=id;
this.manufacturer=manufacturer;
}
public static VehicleDTOBuilder newBuilder()
{
return new VehicleDTOBuilder();
}
public Long getvehicleid() {
return vehicleid;
}
public String getvehcilenumber() {
return vehcilenumber;
}
public EngineType getEnginetype() {
return enginetype;
}
public Integer getRating() {
return rating;
}
public Manufacturer getManufacture() {
return manufacturer;
}
#JsonPOJOBuilder(buildMethodName = "createVehicleDTO", withPrefix = "set")
public static class VehicleDTOBuilder{
private Long vehicleid;
private String vehcilenumber;
private EngineType enginetype;
private Integer rating;
private Manufacturer manufacturer;
public VehicleDTOBuilder setvehicleid(Long id) {
this.vehicleid = id;
return this;
}
public VehicleDTOBuilder setvehcilenumber(String vehcilenumber) {
this.vehcilenumber = vehcilenumber;
return this;
}
public VehicleDTOBuilder setEnginetype(EngineType enginetype) {
this.enginetype = enginetype;
return this;
}
public VehicleDTOBuilder setRating(Integer rating) {
this.rating = rating;
return this;
}
public VehicleDTOBuilder setManufacturer(Manufacturer manufacturer) {
this.manufacturer = manufacturer;
return this;
}
public VehicleDTO createVehicleDTO()
{
return new VehicleDTO(vehicleid, vehcilenumber, enginetype,rating,manufacturer);
}
}
}
And my ManagerDTO is below. This has reference of Vehcile DTO
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.VehicleDO;
import javax.validation.constraints.NotNull;
#JsonInclude(JsonInclude.Include.NON_NULL)
public class ManagerDTO {
#JsonIgnore
private Long id;
#NotNull(message = "Username can not be null!")
private String username;
#NotNull(message = "Password can not be null!")
private String password;
private VehicleDO vehicle;
private ManagerDTO() {
}
private ManagerDTO(Long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
private ManagerDTO(Long id, String username, String password,VehicleDO vehicle) {
this.id = id;
this.username = username;
this.password = password;
this.vehicle = vehicle;
}
public static ManagerDTOBuilder newBuilder() {
return new ManagerDTOBuilder();
}
#JsonProperty
public Long getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public VehicleDO getvehicle() {
return vehicle;
}
public static class ManagerDTOBuilder {
private Long id;
private String username;
private String password;
private VehicleDO vehicle;
public ManagerDTOBuilder setId(Long id) {
this.id = id;
return this;
}
public ManagerDTOBuilder setvehicle(VehicleDO vehicle) {
this.vehicle = vehicle;
return this;
}
public ManagerDTOBuilder setUsername(String username) {
this.username = username;
return this;
}
public ManagerDTOBuilder setPassword(String password) {
this.password = password;
return this;
}
public ManagerDTO createManagerDTO() {
return new ManagerDTO(id, username, password,vehicle);
}
}
}
And my controller is below
#PostMapping("/add")
public void mapVehicleAndManager(#Valid #RequestBody ManagerDTO managerDTO)
{
System.out.println("Print: "+managerDTO.getvehicle().getvehicleId());//this print null
}
So when my controller is called i can see username and password are populated where as vehicle is not populated. A not sure what am missing here and reason why jackson is not populating my java object.

Related

NotBlank validation error in float java (spring boot)

I'm trying to develop an API with an order model and one of the requirements in my model is "price" which takes a float instead of a string
this is the model
package com.api.order_control.models;
import jakarta.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.UUID;
#Entity
#Table(name = "TB_ORDER")
public class OrderModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#Column(nullable = false, length = 11)
private String customerName;
#Column(nullable = false, length = 15)
private String phoneNumber;
#Column(nullable = false, length = 25)
private String address;
#Column(nullable = false, length = 10)
private String doorNumber;
#Column(nullable = true, length = 5)
private String block;
#Column(nullable = false, length = 30)
private String order;
#Column(nullable = false)
private Float price;
#Column(nullable = false)
private LocalDateTime registrationDate;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDoorNumber() {
return doorNumber;
}
public void setDoorNumber(String doorNumber) {
this.doorNumber = doorNumber;
}
public String getBlock() {
return block;
}
public void setBlock(String block) {
this.block = block;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public LocalDateTime getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(LocalDateTime registrationDate) {
this.registrationDate = registrationDate;
}
}
this is the dto package
package com.api.order_control.dtos;
import jakarta.validation.constraints.NotBlank;
public class OrderDto {
#NotBlank
private String customerName;
#NotBlank
private String phoneNumber;
#NotBlank
private String address;
#NotBlank
private String doorNumber;
#NotBlank
private String block;
#NotBlank
private String order;
#NotBlank
private Float price;
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String doorNumber() {
return doorNumber;
}
public void doorNumber(String doorName) {
this.doorNumber = doorName;
}
public String getBlock() {
return block;
}
public void setBlock(String block) {
this.block = block;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
}
I created my post method in my controller, but when I test it in my postman I get this error in the terminal:
jakarta.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'jakarta.validation.constraints.NotBlank' validating type 'java.lang.Float'. Check configuration for 'price'
I understand that the problem is in float, but I can't understand what's wrong with this code.
update: controller
package com.api.order_control.controllers;
import com.api.order_control.dtos.OrderDto;
import com.api.order_control.models.OrderModel;
import com.api.order_control.services.OrderService;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
#RestController
#CrossOrigin(origins = "*", maxAge = 3600)
#RequestMapping("/order")
public class OrderController {
final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
#PostMapping
public ResponseEntity<Object> saveOrder(#RequestBody #Valid OrderDto orderDto) {
var orderModel = new OrderModel();
BeanUtils.copyProperties(orderDto, orderModel);
orderModel.setRegistrationDate(LocalDateTime.now(ZoneId.of("UTC")));
return ResponseEntity.status(HttpStatus.CREATED).body(orderService.save(orderModel));
}
}
You need to use #NotNull for Float. The documentation for #NotBlank states:
The annotated element must not be null and must contain at least one non-whitespace character. Accepts CharSequence.
So, as long as you don't use #NotBlank on a String or Char it won't work.
If you need additional validations on the value of the float, you can use #Min, #Max, #Positive and more.

Java defining generic class as parameter for static method, to pass entity objects

Dear Stackoverflow community,
I am new to working with generics and have problems with using genericts correctly. What I want to do is, that a static method can take a generic Object as a parameter. My idea is, to pass Entity Objects as parameter and after return a UserDetailsImpl object. So I want to make this method able to handle different entity classes and dont write boilerplatecode. For this I write an easy Box class for it.
Box.java
public class Box<T> {
// T stands for "Type"
private T t;
public void set(T t) { this.t = t; }
public T get() { return t; }
}
Now I try to use it to pass generic object as parameter in my UserDetailsImpl.java class in the static build method:
package com.yildiz.tradilianz.security.services;
import java.util.Collection;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import com.fasterxml.jackson.annotation.JsonIgnore;
public class UserDetailsImpl implements UserDetails {
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String email;
#JsonIgnore
private String password;
private Collection<? extends GrantedAuthority> authorities;
public UserDetailsImpl(Long id, String username, String email, String password,
Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.username = username;
this.email = email;
this.password = password;
this.authorities = authorities;
}
public static UserDetailsImpl build(Box<Object> user) {
List<GrantedAuthority> authorities = user.getRoles().stream()
.map(role -> new SimpleGrantedAuthority(role.getName().name()))
.collect(Collectors.toList());
return new UserDetailsImpl(
user.getId(),
user.getUsername(),
user.getEmail(),
user.getPassword(),
authorities);
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
public Long getId() {
return id;
}
public String getEmail() {
return email;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getUsername() {
return username;
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
#Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
UserDetailsImpl user = (UserDetailsImpl) o;
return Objects.equals(id, user.id);
}
}
Now the problem is, that the passed Object doesn't know the whole get() methods I try to access like user.getId(), user.getRoles(), user.getPassword() etc. I want that the generic Box Class contains any Object but how to declare this method I need to access from it?
Otherwise it ends up with "The method getRoles() is undefined for the type Box"
What I wanted to pass as generic Object is my customer entity class, but if it returns null instead i want to test if retailer entity class works and so on in **UserDetailsServiceImpl **:
package com.yildiz.tradilianz.security.services;
import org.apache.commons.validator.routines.EmailValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yildiz.tradilianz.auth.User;
import com.yildiz.tradilianz.auth.UserRepository;
import com.yildiz.tradilianz.customer.Customer;
import com.yildiz.tradilianz.customer.CustomerDTO;
import com.yildiz.tradilianz.customer.CustomerRepository;
#Service
public class UserDetailsServiceImpl implements UserDetailsService {
#Autowired
CustomerRepository customerRepository;
#Autowired
CustomerDTO customerDTO;
#Override
#Transactional
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Check for username or email passed through username parameter
boolean valid = EmailValidator.getInstance().isValid(username);
if (valid == false) {
/*
* Build with UserDetailsImpl but if user for Customer class is null I want to try another repository and do
* something like this:
* Retailer user = retailerRepository.findByUsername(username); And if it is not null
* it should pass user Object which class is Retailer and so on.
*
*/
Customer user = customerRepository.findByUsername(username);
return UserDetailsImpl.build(user);
} else {
Customer user = customerRepository.findByEmail(username):
return UserDetailsImpl.build(user);
}
}
}
customer entity class
package com.yildiz.tradilianz.customer;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.Set;
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.JoinTable;
import javax.persistence.ManyToMany;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import org.hibernate.annotations.CreationTimestamp;
import com.yildiz.tradilianz.auth.ERole;
#Entity
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#NotBlank
#Size(max = 20)
private String username;
#NotBlank
#Size(max = 120)
private String password;
#Column(nullable = false)
private String givenName;
#Column(nullable = false)
private String surname;
private String birthday;
private String streetAddress;
private String city;
private String postalCode;
#Column(updatable = false, nullable = false)
private String email;
private String phoneNumber;
#CreationTimestamp
private Timestamp timestamp;
private Double balance;
private Integer bonuspoints;
private String role;
protected Customer() {
}
public Customer(String username,String password, String givenName, String surname, String birthday, String streetAddress, String city,
String postalCode, String email, String phoneNumber, Double balance, Integer bonuspoints, String role) {
this.username = username;
this.password = password;
this.givenName = givenName;
this.surname = surname;
this.birthday = birthday;
this.streetAddress = streetAddress;
this.city = city;
this.postalCode = postalCode;
this.email = email;
this.phoneNumber = phoneNumber;
this.balance = balance;
this.bonuspoints = bonuspoints;
this.role = role;
}
#Override
public String toString() {
return ("Benutzername: "+username+ "Passwort: "+password+ "Vorname: " + givenName + " Nachname: " + surname +
" Geburtstag: " + birthday + " Straße: "+ streetAddress + " Stadt: " + city + " Postleitzahl: " +
postalCode + " E-Mail-Adresse: " + email+ " Telefonnummer: " + phoneNumber + "Kontostand: " + balance +
" Bonuspunkte: " + bonuspoints+" Rolle:"+role);
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public Long getId() {
return id;
}
public String getGivenName() {
return givenName;
}
public String getSurname() {
return surname;
}
public String getBirthday() {
return birthday;
}
public String getStreetAddress() {
return streetAddress;
}
public String getCity() {
return city;
}
public String getPostalCode() {
return postalCode;
}
public String getEmail() {
return email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public Timestamp getTimestamp() {
return timestamp;
}
public Integer getBonuspoints() {
return bonuspoints;
}
public Double getBalance() {
return balance;
}
public String getRole() {
return role;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public void setStreetAddress(String streetAddress) {
this.streetAddress = streetAddress;
}
public void setCity(String city) {
this.city = city;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public void setEmail(String email) {
this.email = email;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setBalance(Double balance) {
this.balance = balance;
}
public void setBonuspoints(Integer bonuspoints) {
this.bonuspoints = bonuspoints;
}
public void setRole(String role) {
this.role = role;
}
}
**
Can you pls give me tipps how I do it the right way?
in your build() method, you are passing Box, so it only knows the type as Object.
public static UserDetailsImpl build(Box<Object> user)
when you try to access it, you are trying to access the methods from type Customer, which it will not have any clue what methods are associated with Customer object. (user reference will only know about Box class methods)
so, what you need to do is change Box<Object> to Box<Customer> and then access the Customer's methods using
user.get().getId() etc.
here user.get() will return the underlying type object and you will have access to its methods.
or what you can also do is if you want the generic type to be a specific instance type, you can change your Box class implementation to be (extends T type to an instance of that class), for e.g. Customer in your case. (you ca create an interface or abstract class that will have methods that you are trying to use)
public class Box< T extends Customer>
public class Box<T extends CustomerInterface> etc.

Store string of array from json response in realm

This is my JSON response which I need to store in realm.
{
"account": {
"_id": "xx123",
"user_id": "abc999",
"accounts": [
{
"email": "random12#gmail.com",
"email_platform": [
"email"
]
}
]
}
}
As we can not store List<String> I have created a custom class for string value using this example but it gives me following error
java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 199 path $.data.account.accounts[0].email_platform[0]:
public class StringClassEmail extends RealmObject{
private String emailVal;
public StringClassEmail() {
}
public StringClassEmail(String emailVal) {
this.emailVal = emailVal;
}
}
here is also accounst class if required
public class UserAccountList extends RealmObject {
#SerializedName("email")
#Expose
private String email;
#SerializedName("email_platform")
#Expose
private RealmList<StringClassEmail> emailPlatform;
//getter and setter
}
First you should generate your DTOs with jsonschema2pojo
-----------------------------------com.example.Account.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class AccountDTO {
#SerializedName("_id")
#Expose
private String id;
#SerializedName("user_id")
#Expose
private String userId;
#SerializedName("accounts")
#Expose
private List<EmailDTO> emails = null;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public List<EmailDTO> getEmails() {
return emails;
}
public void setAccounts(List<EmailDTO> emails) {
this.emails = emails;
}
}
-----------------------------------com.example.Account_.java-----------------------------------
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class EmailDTO {
#SerializedName("email")
#Expose
private String email;
#SerializedName("email_platform")
#Expose
private List<String> emailPlatform = null;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<String> getEmailPlatform() {
return emailPlatform;
}
public void setEmailPlatform(List<String> emailPlatform) {
this.emailPlatform = emailPlatform;
}
}
-----------------------------------com.example.Response.java-----------------------------------
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Response {
#SerializedName("account")
#Expose
private AccountDTO account;
public AccountDTO getAccount() {
return account;
}
public void setAccount(AccountDTO account) {
this.account = account;
}
}
Then define RealmObject classes as well
public class Account extends RealmObject {
#PrimaryKey
private String id;
#Index
private String userId;
private User user;
private RealmList<Email> emails = null;
}
public class Email extends RealmObject {
#Index
private String email;
private RealmList<EmailPlatform> emailPlatform;
}
public class EmailPlatform extends RealmObject {
#Index
private String platform;
private Email email;
}
And then parse the JSON with GSON, then map it over to Realm's schema, then insert it to db.

Not able to set location model to null in contact entity

I am working on a spring mvc app in which I have 2 model classes. Following are my model classes:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
#Entity
#Table(name="Contact")
public class ContactModel {
#Id
#Column(name="contactid")
#GeneratedValue
private int contactId;
#Column(name="contactname")
private String contactName;
#Column(name="contactemail")
private String email;
#Column(name="contactphone")
private String phone;
#ManyToOne
#JoinColumn(name="locationid")
private LocationModel locationModel;
public LocationModel getLocationModel() {
return locationModel;
}
public void setLocationModel(LocationModel locationModel) {
this.locationModel = locationModel;
}
public int getContactId() {
return contactId;
}
public void setContactId(int contactId) {
this.contactId = contactId;
}
public String getContactName() {
return contactName;
}
public void setContactName(String contactName) {
this.contactName = contactName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
and LocationModel
import java.util.List;
//import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.Cascade;
#Entity
#Table(name="Location")
public class LocationModel {
#Id
#Column(name="locationid")
#GeneratedValue
private int locationId;
#Column(name="locationname")
private String locationName;
#Column(name="locationdesc")
private String locationDescription;
#Column(name="type")
private String locationType;
#Column(name="address")
private String address;
#Column(name="city")
private String city;
#Column(name="state")
private String state;
#Column(name="district")
private String district;
#Column(name="lattitude")
private String lattitude;
#Column(name="longitude")
private String longitude;
#OneToMany(mappedBy = "locationModel")
private List<ContactModel> contactList;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getLattitude() {
return lattitude;
}
public void setLattitude(String lattitude) {
this.lattitude = lattitude;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
public String getLocationType() {
return locationType;
}
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 getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public void setLocationType(String locationType) {
this.locationType = locationType;
}
public int getLocationId() {
return locationId;
}
public void setLocationId(int locationId) {
this.locationId = locationId;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getLocationDescription() {
return locationDescription;
}
public void setLocationDescription(String locationDescription) {
this.locationDescription = locationDescription;
}
}
On deleting location I want to set location of corresponding contacts to null. I am using following code for this:
public void selLocationToNull(int locationId) throws Exception {
try {
logger.info("deleteContact() begins:");
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("update ContactModel set locationModel=:newLocation where locationModel=:locationId");
query.setParameter("newLocation", null);
query.setParameter("locationId", locationId);
query.executeUpdate();
logger.info("null update query executed...");
} catch (Exception e) {
logger.debug("Error while updating location to null: "
+ e.getMessage());
throw e;
} finally {
}
}
I am getting exception for this:
org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.bizmerlin.scm.model.LocationModel.locationId
Caused by: java.lang.IllegalArgumentException: Can not set int field com.bizmerlin.scm.model.LocationModel.locationId to java.lang.Integer
I have getter method for locationId in my LocationModel class.
How can you set a null to a primitive type? It is generally good practice to use wrapper types for fields in your Entity.
#Id
#Column(name="locationid")
#GeneratedValue
private Integer locationId;
You set in the query's where LocationModel and compare it with int. SHould be
Query query = session.createQuery("update ContactModel set locationModel=:newLocation where locationModel.id=:locationId");
instead. Or pass the LocationModel instance rather than id

Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)

I have spring application everytime I run and I try to login I got the following excpetion after login
java.lang.IllegalStateException: Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)
at com.emc.fleet.domain.User_Roo_Jpa_ActiveRecord.ajc$interMethod$com_emc_fleet_domain_User_Roo_Jpa_ActiveRecord$com_emc_fleet_domain_User$entityManager(User_Roo_Jpa_ActiveRecord.aj:19)
at com.emc.fleet.domain.User.entityManager(User.java:1)
at com.emc.fleet.domain.User_Roo_Jpa_ActiveRecord.ajc$interMethodDispatch1$com_emc_fleet_domain_User_Roo_Jpa_ActiveRecord$com_emc_fleet_domain_User$entityManager(User_Roo_Jpa_ActiveRecord.aj)
at com.emc.fleet.domain.User_Roo_Finder.ajc$interMethod$com_emc_fleet_domain_User_Roo_Finder$com_emc_fleet_domain_User$findUsersByUserIdEquals(User_Roo_Finder.aj:47)
at com.emc.fleet.domain.User.findUsersByUserIdEquals(User.java:1)
I have read many STO questions and checked all answers none of them succeded
this is my user class
package com.emc.fleet.domain
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Transient;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
#RooJavaBean
#RooToString
#RooJpaActiveRecord(finders = { "findUsersByEmailLike", "findUsersByUserIdEquals", "findUsersByCostCenter", "findUsersByDepartmet" })
public class User {
#Id
#GeneratedValue
private Long id;
#NotEmpty
#NotNull
private String firstName;
#NotEmpty
#NotNull
private String lastName;
#NotNull
private Long userId;
#Email
#NotNull
private String email;
#NotNull
private String address;
#NotNull
private String district;
private String deskPhone;
#NotEmpty
#NotNull
private String mobile;
#NotEmpty
#NotNull
private String password;
#Transient
private String retypePassword;
#OneToOne
private Department departmet;
#OneToOne
#JoinColumn(name = "cost_center")
private CostCenter costCenter;
private String managerName;
private boolean enabled = true;
#Enumerated(EnumType.STRING)
private Roles role = Roles.ROLE_USER;
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 Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDistrict() {
return district;
}
public void setDistrict(String district) {
this.district = district;
}
public String getDeskPhone() {
return deskPhone;
}
public void setDeskPhone(String deskPhone) {
this.deskPhone = deskPhone;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRetypePassword() {
return retypePassword;
}
public void setRetypePassword(String retypePassword) {
this.retypePassword = retypePassword;
}
public Department getDepartmet() {
return departmet;
}
public void setDepartmet(Department departmet) {
this.departmet = departmet;
}
public CostCenter getCostCenter() {
return costCenter;
}
public void setCostCenter(CostCenter costCenter) {
this.costCenter = costCenter;
}
public String getManagerName() {
return managerName;
}
public void setManagerName(String managerName) {
this.managerName = managerName;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Roles getRole() {
return role;
}
public void setRole(Roles role) {
this.role = role;
}
#Override
public String toString() {
return getEmail() + " - " + getUserId();
}
}
and this the user_Roo_Configurable file
package com.emc.fleet.domain;
import com.emc.fleet.domain.User;
import org.springframework.beans.factory.annotation.Configurable;
privileged aspect User_Roo_Configurable {
declare #type: User: #Configurable;
}
any clue ?

Categories