Deserialize Exception in spring hibernate with OneToOne Mapping - java

I am using Spring boot 2.1.2 with hibernate , and i have simple two model classes like user and user account, and these 2 models are connected with oneToOne mapping. When we call user, i need to get user account also. I just mapped user account model to user model with oneToOne mapping. But when i call user am facing one Deserialize Exception.
User model
import java.io.Serializable;
import java.util.Calendar;
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;
#Entity
#Table(name = "tbl_user")
public class User implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#OneToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "user_account_id")
UserAccount userAccount;
#Column(name = "first_name",nullable = false)
private String firstName;
#Column(name = "active",nullable = false)
private Integer active;
#Column(name = "created_date",nullable = false)
private Calendar createdDate;
#Column(name = "created_by",nullable = false)
private Integer created_by;
#Column(name = "updated_date")
private Calendar updatedDate;
#Column(name = "updated_by")
private Integer updated_by;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(Integer id, UserAccount userAccount, String firstName, Integer active, Calendar createdDate,
Integer created_by, Calendar updatedDate, Integer updated_by) {
super();
this.id = id;
this.userAccount = userAccount;
this.firstName = firstName;
this.active = active;
this.createdDate = createdDate;
this.created_by = created_by;
this.updatedDate = updatedDate;
this.updated_by = updated_by;
}
public Integer getId() {
return id;
}
public UserAccount getUserAccount() {
return userAccount;
}
public void setUserAccount(UserAccount userAccount) {
this.userAccount = userAccount;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public Calendar getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Calendar createdDate) {
this.createdDate = createdDate;
}
public Integer getCreated_by() {
return created_by;
}
public void setCreated_by(Integer created_by) {
this.created_by = created_by;
}
public Calendar getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Calendar updatedDate) {
this.updatedDate = updatedDate;
}
public Integer getUpdated_by() {
return updated_by;
}
public void setUpdated_by(Integer updated_by) {
this.updated_by = updated_by;
}
}
UserAccount Model
import java.io.Serializable;
import java.util.Calendar;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "tbl_user_account")
public class UserAccount implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private Integer id;
#Column(name = "usere_name",nullable = false)
UserAccount usereName;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "active",nullable = false)
private Integer active;
#Column(name = "created_date",nullable = false)
private Calendar createdDate;
#Column(name = "created_by",nullable = false)
private Integer created_by;
#Column(name = "updated_date")
private Calendar updatedDate;
#Column(name = "updated_by")
private Integer updated_by;
public UserAccount(Integer id, UserAccount usereName, String password,Integer active,
Calendar createdDate, Integer created_by, Calendar updatedDate, Integer updated_by) {
super();
this.id = id;
this.usereName = usereName;
this.password = password;
this.active = active;
this.createdDate = createdDate;
this.created_by = created_by;
this.updatedDate = updatedDate;
this.updated_by = updated_by;
}
public UserAccount() {
super();
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public UserAccount getUsereName() {
return usereName;
}
public void setUsereName(UserAccount usereName) {
this.usereName = usereName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getActive() {
return active;
}
public void setActive(Integer active) {
this.active = active;
}
public Calendar getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Calendar createdDate) {
this.createdDate = createdDate;
}
public Integer getCreated_by() {
return created_by;
}
public void setCreated_by(Integer created_by) {
this.created_by = created_by;
}
public Calendar getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Calendar updatedDate) {
this.updatedDate = updatedDate;
}
public Integer getUpdated_by() {
return updated_by;
}
public void setUpdated_by(Integer updated_by) {
this.updated_by = updated_by;
}
}
Property file
# Application running port
server.port=8000
# Application running port
server.servlet.contextPath=/app
# Log files
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
#DB config
spring.datasource.url=jdbc:mysql://localhost:3306/db_name
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect

The problem seems to be in UserAccount class, where you defined usereName field as UserAccount type.
I think it should be a String.

Related

Getting an error about not having an Identifier even when I have one

This is my UserRole class. Here, the id_roles, id_users and updated_by are supposed to be foreign keys (id_roles coming from the Role table and the other two coming from the User table, I'll put the code for each one of the tables down below)
package offgrid.models;
import io.quarkus.hibernate.reactive.panache.PanacheEntityBase;
import javax.persistence.*;
import java.time.LocalDateTime;
#Entity
#Access(AccessType.PROPERTY)
#Table(name = "user_roles")
public class UserRole extends PanacheEntityBase {
#EmbeddedId
private UserRolePK UserRolePK;
#OneToOne
#JoinColumn(name = "id_roles", referencedColumnName = "id")
private Role roleId;
#OneToOne
#JoinColumn(name = "id_users", referencedColumnName = "id")
private User userId;
#Column(name = "created_at")
private LocalDateTime createdAt;
#Column(name = "updated_at")
private LocalDateTime updatedAt;
#ManyToOne
#JoinColumn(name = "update_by", referencedColumnName = "name")
private User updatedBy;
public offgrid.models.UserRolePK getUserRolePK() {
return UserRolePK;
}
public void setUserRolePK(offgrid.models.UserRolePK userRolePK) {
UserRolePK = userRolePK;
}
public Role getRoleId() {
return roleId;
}
public void setRoleId(Role roleId) {
this.roleId = roleId;
}
public User getUserId() {
return userId;
}
public void setUserId(User userId) {
this.userId = userId;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public User getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(User updatedBy) {
this.updatedBy = updatedBy;
}
}
And this is my UserRolePK
package offgrid.models;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;
#Embeddable
public class UserRolePK implements Serializable {
#Column(name = "user_id")
private Long userId;
#Column(name = "role_id")
private Long roleId;
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserRolePK that = (UserRolePK) o;
return userId.equals(that.userId) && roleId.equals(that.roleId);
}
#Override
public int hashCode() {
return Objects.hash(userId, roleId);
}
}
Here is my User class
package offgrid.models;
import io.quarkus.hibernate.reactive.panache.PanacheEntityBase;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import javax.persistence.*;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.UUID;
#Entity
#Table(name="users")
public class User extends PanacheEntityBase {
#Id
#Column(name = "id")
#GeneratedValue(generator = "UUID")
#GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
#Type(type = "pg-uuid")
private UUID id;
#Column(name = "user")
private String username;
#Column(name = "name")
private String name;
#Column(name = "date_of_birth")
private LocalDate dateOfBirth;
#Column(name = "photo")
private String photo;
#Column(name = "tax_id")
private String taxId;
#Column(name = "status")
private String status;
#Column(name = "created_at")
private LocalDateTime createdAt;
#Column(name = "updated_at")
private LocalDateTime updateAt;
#ManyToOne
#JoinColumn(name = "updated_by")
private User user;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(LocalDate dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getPhoto() {
return photo;
}
public void setPhoto(String photo) {
this.photo = photo;
}
public String getTaxId() {
return taxId;
}
public void setTaxId(String taxId) {
this.taxId = taxId;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdateAt() {
return updateAt;
}
public void setUpdateAt(LocalDateTime updateAt) {
this.updateAt = updateAt;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
And the Role class
package offgrid.models;
import io.quarkus.hibernate.reactive.panache.PanacheEntityBase;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.UUID;
#Entity
#Table(name = "roles")
public class Role extends PanacheEntityBase {
#Id
#Column(name = "id")
#GeneratedValue(generator = "UUID")
#GenericGenerator(
name = "UUID",
strategy = "org.hibernate.id.UUIDGenerator"
)
#Type(type = "pg-uuid")
private UUID id;
#Column(name = "name")
private String name;
#Column(name = "created_at")
private LocalDateTime createdAt;
#Column(name = "updated_at")
private LocalDateTime updatedAt;
#ManyToOne
#JoinColumn(name = "updated_by")
private User updatedBy;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public void setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
}
public LocalDateTime getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(LocalDateTime updatedAt) {
this.updatedAt = updatedAt;
}
public User getUpdatedBy() {
return updatedBy;
}
public void setUpdatedBy(User updatedBy) {
this.updatedBy = updatedBy;
}
}
I'm getting this error when I try to run my code:
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: offgrid.models.UserRole
But as I detailed above, there I put an EmbeddedId annotation referencing my UserRolePK class.. Am I missing something?
It's because of:
#Access(AccessType.PROPERTY)
But you used annotations on fields.
Change it to:
#Access(AccessType.FIELD)
or remove it, as JPA know it is FIELD base on where you placed the annotations.

Java-Oracle - Unable to create specific table

I always get error java.sql.SQLSyntaxErrorException: ORA-00904: : invalid identifier and java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist when creating table. This is some of my tables
package com.domibowo.salestracking.models;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.List;
#Entity
#Table(schema = "SALES_TRACKING", name="CUSTOMER")
public class Customer {
#Id
#GeneratedValue(generator = "seq", strategy= GenerationType.SEQUENCE)
#SequenceGenerator(name="seq", sequenceName = "SEQ1")
private Long id;
#Column(name="citizen_id")
private Long citizenId;
#Column(name = "full_name")
private String fullName;
#Column(name = "address")
private String address;
#Column(name="city")
private String city;
#ManyToOne
#JoinColumn(name="region_id")
#JsonIgnoreProperties(value = {"salesList","customerList"})
private Region region;
#Transient
private Long regionId;
#OneToMany(mappedBy = "customer")
private List<Details> details;
public Customer() {
}
public Customer(Long id, Long citizenId, String fullName, String address, String city, Region region, Long regionId, List<Details> details) {
this.id = id;
this.citizenId = citizenId;
this.fullName = fullName;
this.address = address;
this.city = city;
this.region = region;
this.regionId = regionId;
this.details = details;
}
public Long getId() {
return id;
}
public Long getCitizenId() {
return citizenId;
}
public void setCitizenId(Long citizen_id) {
this.citizenId = citizen_id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String full_name) {
this.fullName = full_name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Region getRegion() {
return region;
}
public void setRegion(Region region) {
this.region = region;
}
public List<Details> getDetails() {
return details;
}
public void setDetails(List<Details> details) {
this.details = details;
}
public Long getRegionId() {
return regionId;
}
public void setRegionId(Long regionId) {
this.regionId = regionId;
}
}
The product table and the rest are able to create without any problem.
But this,
package com.domibowo.salestracking.models;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.time.LocalDate;
#Entity
#Table(schema = "SALES_TRACKING",name="HISTORY")
public class History {
#Id
#GeneratedValue(generator = "seq", strategy= GenerationType.SEQUENCE)
#SequenceGenerator(name="seq", sequenceName = "SEQ1")
private Long id;
#ManyToOne
#JoinColumn(name = "sales_id")
#JsonIgnoreProperties(value = {"region"})
private Sales sales;
#OneToOne
#JoinColumn(name = "details_id")
#JsonIgnoreProperties(value = {"history"})
private Details details;
#Column(name = "date")
#JsonFormat(pattern = "dd/MM/yyyy")
private LocalDate date;
#Column(name = "total")
private Double total;
#Transient
private Long detailsId;
#Transient
private Long salesId;
public History() {
}
public History(Long id, Sales sales, Long salesId, Details details, LocalDate date, Double total, Long detailsId) {
this.id = id;
this.sales = sales;
this.details = details;
this.date = date;
this.total = total;
this.detailsId = detailsId;
this.salesId = salesId;
}
public Long getDetailsId() {
return detailsId;
}
public void setDetailsId(Long detailsId) {
this.detailsId = detailsId;
}
public Long getId() {
return id;
}
public Sales getSales() {
return sales;
}
public void setSales(Sales sales) {
this.sales = sales;
}
public Details getDetails() {
return details;
}
public void setDetails(Details details) {
this.details = details;
}
public Double getTotal() {
return total;
}
public void setTotal(Double total) {
this.total = total;
}
public LocalDate getDate() {
return date;
}
public void setDate(LocalDate date) {
this.date = date;
}
public Long getSalesId() {
return salesId;
}
public void setSalesId(Long salesId) {
this.salesId = salesId;
}
}
I always get ORA-00904 and ORA-00942 errors when creating History table even if the generator id used is the same as others. Any help much appreciated!!
Even while using Hibernate JPA you must not forget you use the Oracle database and you must avoid using reserved words as columns names.
So please review all columns names, particularly this one
#Column(name = "date")
The error ORA-00904 invalid identifier point in this direction. DATE is a reserved word and can't be used as column name.
The second one (ORA-00942 table or view does not exist) is a followup message caused by the fact that the table can't be created.

Invalid property 'stateId' of bean class Could not find field for property during fallback access

I'm getting the following error while trying to update a data in DB using SpringBoot
The error is: org.springframework.beans.NotReadablePropertyException: Invalid property 'stateId' of bean class [com.studawn.model.District]: Could not find field for property during fallback access!
I don't know how to fix it.
Controller
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.studawn.exception.StudawnException;
import com.studawn.model.City;
import com.studawn.model.State;
import com.studawn.request.model.DistrictBean;
import com.studawn.request.model.StatePage;
import com.studawn.service.callback.StateCityDistrictService;
import com.studawn.utils.RestUtils;
#CrossOrigin(maxAge = 3600)
#RestController
public class StateCityDistrictController<T> extends RestUtils<T> {
#Autowired
StateCityDistrictService<T> stateCityDistrictService;
#RequestMapping(value = "/updateState", method = RequestMethod.POST, headers = "Accept=application/json")
public #ResponseBody Object updateState(#RequestBody State state) {
try {
return getSuccessResponse(stateCityDistrictService.updateState(state));
} catch (StudawnException e) {
return getErrorResponse(e.getMessage());
}
}
}
Service class
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.studawn.combined.repository.CityRepository;
import com.studawn.combined.repository.DistrictRepository;
import com.studawn.combined.repository.StateRepository;
import com.studawn.exception.StudawnException;
import com.studawn.model.AdminUser;
import com.studawn.model.City;
import com.studawn.model.District;
import com.studawn.model.State;
import com.studawn.request.model.DistrictBean;
import com.studawn.request.model.StatePage;
import com.studawn.service.callback.StateCityDistrictService;
import com.studawn.utils.Constant;
import com.studawn.utils.ErrorCode;
#Service
public class StateCityDistrictImpl<T> implements StateCityDistrictService<T>, Constant {
#Autowired
StateRepository stateRepository;
#Autowired
CityRepository cityRepository;
#Autowired
DistrictRepository districtRepository;
#Transactional
#Override
public Object updateDistrict(DistrictBean districtBean) throws StudawnException {
if (districtRepository.isDistrictCodeExists(districtBean.getDistrictCode()) > 0)
throw new StudawnException(ErrorCode.DISTRICT_CODE_ALREADY_EXISTS);
else {
District district = new District();
district.setDistrictId(districtBean.getDistrictId());
district.setDistrictName(districtBean.getDistrictName());
district.setDistrictCode(districtBean.getDistrictCode());
AdminUser adminUser = new AdminUser();
adminUser.setLogInId(districtBean.getLastUpdatedBy());
district.setLastUpdatedBy(adminUser);
State state = new State();
state.setStateId(districtBean.getStateId());
district.setState(state);
return stateRepository.saveAndFlush(district);
}
}
}
District Entity
#Entity
#Table(name = "district")
public class District {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "district_id")
private int districtId;
#Column(name = "district_name", length = 45)
private String districtName;
#Column(name = "district_code", length = 45)
private String districtCode;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_date", nullable = false, updatable = false)
#CreatedDate
private Date dateCreated;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "modified_date")
#LastModifiedDate
private Date dateModified;
#JsonBackReference(value = "createdBy")
#ManyToOne
#JoinColumn(name = "created_by", updatable = false, nullable = false)
private AdminUser createdBy;
#JsonBackReference(value = "lastUpdatedBy")
#ManyToOne
#JoinColumn(name = "last_updated_by")
private AdminUser lastUpdatedBy;
#JsonIgnore
#OneToMany(mappedBy = "district", fetch = FetchType.LAZY)
private Set<City> cityList;
#JsonBackReference(value = "stateId")
#ManyToOne
#JoinColumn(name = "state_id")
private State state;
#JsonIgnore
#OneToMany(mappedBy = "district")
private Set<Pincode> pincode;
#JsonIgnore
#OneToMany(mappedBy = "district")
private List<College> college;
#JsonIgnore
public Set<City> getCity() {
return cityList;
}
public void setCity(Set<City> cityList) {
this.cityList = cityList;
}
public String getDistrictCode() {
return districtCode;
}
public void setDistrictCode(String districtCode) {
this.districtCode = districtCode;
}
public List<College> getCollege() {
return college;
}
public void setCollege(List<College> college) {
this.college = college;
}
public Set<Pincode> getPincode() {
return pincode;
}
public void setPincode(Set<Pincode> pincode) {
this.pincode = pincode;
}
public int getDistrictId() {
return districtId;
}
public void setDistrictId(int districtId) {
this.districtId = districtId;
}
public String getDistrictName() {
return districtName;
}
public void setDistrictName(String districtName) {
this.districtName = districtName;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getDateModified() {
return dateModified;
}
public void setDateModified(Date dateModified) {
this.dateModified = dateModified;
}
public AdminUser getCreatedBy() {
return createdBy;
}
public void setCreatedBy(AdminUser createdBy) {
this.createdBy = createdBy;
}
public AdminUser getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(AdminUser lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public Set<City> getCityList() {
return cityList;
}
public void setCityList(Set<City> cityList) {
this.cityList = cityList;
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
}
State Entity
#Entity
#Table(name = "state")
public class State {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "state_id")
private int stateId;
#Column(name = "state_name", length = 45)
private String stateName;
#Column(name = "state_code", length = 45)
private String stateCode;
#JsonIgnore
#OneToMany(mappedBy = "state", fetch = FetchType.LAZY)
private Set<City> cityList;
#JsonIgnore
#OneToMany(mappedBy = "state", fetch = FetchType.LAZY)
private Set<District> districtList;
#JsonIgnore
#OneToMany(mappedBy = "state")
private List<College> college;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created_date", nullable = false, updatable = false)
#CreatedDate
private Date dateCreated;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "modified_date")
#LastModifiedDate
private Date dateModified;
#JsonBackReference(value = "createdBy")
#ManyToOne
#JoinColumn(name = "created_by", updatable = false, nullable = false)
private AdminUser createdBy;
#JsonBackReference(value = "lastUpdatedBy")
#ManyToOne
#JoinColumn(name = "last_updated_by")
private AdminUser lastUpdatedBy;
public String getStateCode() {
return stateCode;
}
public void setStateCode(String stateCode) {
this.stateCode = stateCode;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getDateModified() {
return dateModified;
}
public void setDateModified(Date dateModified) {
this.dateModified = dateModified;
}
public AdminUser getCreatedBy() {
return createdBy;
}
public void setCreatedBy(AdminUser createdBy) {
this.createdBy = createdBy;
}
public AdminUser getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(AdminUser lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public List<College> getCollege() {
return college;
}
public void setCollege(List<College> college) {
this.college = college;
}
public int getStateId() {
return stateId;
}
public void setStateId(int stateId) {
this.stateId = stateId;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public void setCityList(Set<City> cityList) {
this.cityList = cityList;
}
public Set<City> getCityList() {
return cityList;
}
public void setDistrictList(Set<District> districtList) {
this.districtList = districtList;
}
public Set<District> getDistrictList() {
return districtList;
}
}
District Bean
public class DistrictBean {
private int districtId;
private String districtName;
private String districtCode;
private String createdBy;
private String lastUpdatedBy;
private int stateId;
public String getDistrictCode() {
return districtCode;
}
public void setDistrictCode(String districtCode) {
this.districtCode = districtCode;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
public String getLastUpdatedBy() {
return lastUpdatedBy;
}
public void setLastUpdatedBy(String lastUpdatedBy) {
this.lastUpdatedBy = lastUpdatedBy;
}
public int getStateId() {
return stateId;
}
public void setStateId(int stateId) {
this.stateId = stateId;
}
public int getDistrictId() {
return districtId;
}
public void setDistrictId(int districtId) {
this.districtId = districtId;
}
public String getDistrictName() {
return districtName;
}
public void setDistrictName(String districtName) {
this.districtName = districtName;
}
}
JSON Request
{
"districtId":1,
"districtCode":"Chn" ,
"districtName":"Chennai",
"lastUpdatedBy":"arun#xyz.com",
"stateId":1
}
Thanks in advance!

Mapped Entity null on #OneToOne with #JoinColumn

I get the mapped entity always null but, FetchType.EAGER is set already. I have a Booking entity class that maps to two other entities - Slot and Subscriber. Both the entities are null when I fetch the booking entity
Booking class
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.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
#Entity
#Table(name = "BOOKING")
public class Booking {
public Booking(){
}
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "id")
private Integer id;
#Column(name = "title")
private String title;
#Column(name = "descr")
private String desc;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "slotid",insertable = false, updatable = false)
private Slot slot;
private Integer slotid;
private Integer subscriberid;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "subscriberid",insertable = false, updatable = false)
private User subscriber;
#Column(name = "created")
#Temporal(TemporalType.TIMESTAMP)
private Date created;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "slotid",referencedColumnName="slotid")
public Slot getSlot() {
return slot;
}
public void setSlot(Slot slot) {
this.slot = slot;
}
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name = "subscriberid",referencedColumnName="userid")
public User getSubscriber() {
return subscriber;
}
public void setSubscriber(User subscriber) {
this.subscriber = subscriber;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Integer getSlotid() {
return slotid;
}
public void setSlotid(Integer slotid) {
this.slotid = slotid;
}
public Integer getSubscriberid() {
return subscriberid;
}
public void setSubscriberid(Integer subscriberid) {
this.subscriberid = subscriberid;
}
}
Slot class
import java.util.Date;
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 javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
#Entity
#Table(name="SLOT")
public class Slot {
public Slot(){
}
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="slotid")
private Integer id;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="ownerid",insertable = false, updatable = false)
private User user;
#Column(name="startdate")
private Date startdate;
#Column(name="enddate")
private Date enddate;
#Column(name="status")
private String status;
private Integer ownerid;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created", nullable = false, updatable=false)
#Version
private Date created;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return this.user;
}
public void setUser(User owner) {
this.user = owner;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Integer getOwnerid() {
return ownerid;
}
public void setOwnerid(Integer ownerid) {
this.ownerid = ownerid;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getStartdate() {
return startdate;
}
public void setStartdate(Date startdate) {
this.startdate = startdate;
}
public Date getEnddate() {
return enddate;
}
public void setEnddate(Date enddate) {
this.enddate = enddate;
}
}
Subscriber - User class
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.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="users")
public class User {
public User(){
}
#Id#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="userid")
private Integer userid = 0;
#Column(name = "name")
private String name;
#Column(name = "mobile")
private String mobile;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Column(name = "type")
private String userType;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="cityid",insertable = false, updatable = false)
private City city;
private String cityid;
#OneToOne(fetch=FetchType.EAGER)
#JoinColumn(name="specialityid",insertable = false, updatable = false)
private Speciality speciality;
private Integer specialityid;
#Column(name="medregno")
private String regno;
#Column(name="refcode")
private String referalcode;
public String getRegno() {
return regno;
}
public void setRegno(String regno) {
this.regno = regno;
}
public String getReferalcode() {
return referalcode;
}
public void setReferalcode(String referalcode) {
this.referalcode = referalcode;
}
#Column(name = "gender")
private String gender;
#Column(name = "active")
private boolean active;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "updated")
private Date updated;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "created")
private Date created;
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (userid != other.userid)
return false;
return true;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public String getCityid() {
return cityid;
}
public void setCityid(String cityid) {
this.cityid = cityid;
}
public Speciality getSpeciality() {
return speciality;
}
public void setSpeciality(Speciality speciality) {
this.speciality = speciality;
}
public Integer getSpecialityid() {
return specialityid;
}
public void setSpecialityid(Integer specialityid) {
this.specialityid = specialityid;
}
}
booking.getSlot() and booking.getSubscriber() returns null
Please let me know if i miss some configuration while mapping
EDIT1
Added code how the entity is getting loaded
public Booking addBooking(String title,String desc,int slotid,int subscriberid,Session session){
Booking booking = new Booking();
booking.setTitle(title);
booking.setDesc(desc);
booking.setSlotid(slotid);
booking.setSubscriberid(subscriberid);
booking.setCreated(new Date());
Integer bookingid = (Integer) session.save(booking);
session.flush();
Booking bookingEntity = (Booking) session.createQuery("From Booking where id = ?").
setParameter(0, bookingid).list().get(0);
return bookingEntity;
}
I am saving the entity and reloading it.
It's not working because Hibernate is retuning the same instance it has already in its 1st level cache, which doesn't have a reference to any of the 2 other entities.
To fix this, you have to do a session.refresh(booking) rather than executing a query.
In your code :
booking.setSlotid(slotid);
booking.setSubscriberid(subscriberid);
You're just setting Integer values and not objects. Instead of this, try to set objects :
booking.setSlot(new Slot(slotid));
booking.setSubscriber(new Subscriber(subscriberid));
But as #Augusto said, the associations you're having in the session (Slot and Subscriber) are not full objects they contain only their ids. That's why you can't get other fields of these objects.

org.hibernate.QueryException: duplicate association path for #ManyToOne Criteria

I have two classes which has a relationship between them. These are
com.edfx.adb.persist.Activity:
package com.edfx.adb.persist.entity;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;
import org.hibernate.annotations.NaturalId;
#javax.persistence.Entity
#Table(name = "ACTIVITY")
public class Activity extends Entity {
#Transient
private static final long serialVersionUID = 4741665931936809028L;
private String activityId;
private String activityName;
private String activityDescription;
private Customer customer;
private ActivityType activityType;
private boolean active;
private Double mandays;
private Double price;
private String manager;
private List<Participation> participations;
public Activity() {
super();
}
#NaturalId
#Column(name = "ACTIVITY_ID", nullable = false)
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
#Lob
#Column(name = "ACTIVITY_NAME", nullable = false)
public String getActivityName() {
return activityName;
}
public void setActivityName(String activityName) {
this.activityName = activityName;
}
#Lob
#Column(name = "ACTIVITY_DESCRIPTION", nullable = false)
public String getActivityDescription() {
return activityDescription;
}
public void setActivityDescription(String activityDescription) {
this.activityDescription = activityDescription;
}
#ManyToOne
#JoinColumn(name = "CUSTOMER_ID", nullable = false)
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
#ManyToOne
#JoinColumn(name = "ACTIVITY_TYPE_ID", nullable = false)
public ActivityType getActivityType() {
return activityType;
}
public void setActivityType(ActivityType activityType) {
this.activityType = activityType;
}
#Column(name = "ACTIVE", nullable = false)
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
#Column(name = "MANDAYS")
public Double getMandays() {
return mandays;
}
public void setMandays(Double mandays) {
this.mandays = mandays;
}
#Column(name = "PRICE")
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
#Column(name = "CUSTOMER_SIDE_MANAGER")
public String getManager() {
return manager;
}
public void setManager(String manager) {
this.manager = manager;
}
#OneToMany(mappedBy = "activity", fetch = FetchType.LAZY)
#Cascade(CascadeType.SAVE_UPDATE)
public List<Participation> getParticipations() {
return participations;
}
public void setParticipations(List<Participation> participations) {
this.participations = participations;
}
}
com.edfx.adb.persist.ActivityType:
package com.edfx.adb.persist.entity;
import javax.persistence.Column;
import javax.persistence.Table;
import javax.persistence.Transient;
#javax.persistence.Entity
#Table(name = "ACTIVITY_TYPE")
public class ActivityType extends Entity {
#Transient
private static final long serialVersionUID = 2322745769010162801L;
private String parent;
private String name;
private String activityId;
public ActivityType() {
}
#Column(name = "PARENT", nullable = false)
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
#Column(name = "NAME", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name = "ACTIVITY_ID", nullable = false)
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
}
Both of them extends com.edfx.adb.persist.entity.Entity:
package com.edfx.adb.persist.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.persistence.Version;
import org.hibernate.proxy.HibernateProxyHelper;
#MappedSuperclass
public class Entity implements Serializable {
#Transient
private static final long serialVersionUID = 7470288121057059283L;
private Long id;
private Date createTimestamp;
private Date lastUpdateTimestamp;
private Long version;
public Entity() {
super();
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", updatable = false, nullable = false, unique = true)
public Long getId() {
return id;
}
#SuppressWarnings("unused")
private void setId(Long id) {
this.id = id;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "CREATE_TIMESTAMP")
public Date getCreateTimestamp() {
return createTimestamp;
}
public void setCreateTimestamp(Date createTimestamp) {
this.createTimestamp = createTimestamp;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_UPDATE_TIMESTAMP")
public Date getLastUpdateTimestamp() {
return lastUpdateTimestamp;
}
public void setLastUpdateTimestamp(Date lastUpdateTimestamp) {
this.lastUpdateTimestamp = lastUpdateTimestamp;
}
#Version
#Column(name = "VERSION")
public Long getVersion() {
return version;
}
#SuppressWarnings("unused")
private void setVersion(Long version) {
this.version = version;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
return prime * result + ((getId() == null) ? super.hashCode() : getId().hashCode());
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!getClass().equals(HibernateProxyHelper.getClassWithoutInitializingProxy(obj))) {
return false;
}
final Entity other = (Entity) obj;
if (getId() != other.getId()) {
if (getId() == null) {
return false;
}
if (!getId().equals(other.getId())) {
return false;
}
}
return true;
}
}
Now I am using Primefaces datatable to show a List<Activity> in which I have filtering on the field name of ActivityType. ActivityType is associated with Activity by #ManyToOne relationship.
For filtering the List<Activity> I am using:
Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Activity.class);
criteria.createCriteria("activityType").add(Restrictions.like("name", value.toString(), MatchMode.START));
I am getting:
null: org.hibernate.QueryException: duplicate association path: activityType
at org.hibernate.loader.criteria.CriteriaQueryTranslator.createAssociationPathCriteriaMap(CriteriaQueryTranslator.java:172) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.loader.criteria.CriteriaQueryTranslator.<init>(CriteriaQueryTranslator.java:111) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.loader.criteria.CriteriaLoader.<init>(CriteriaLoader.java:84) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1602) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374) [hibernate-core-4.1.8.Final.jar:4.1.8.Final]
at com.edfx.adb.dao.ActivityDao.loadActivities(ActivityDao.java:54) [classes:]
at com.edfx.adb.service.ActivityService.loadActivities(ActivityService.java:101) [classes:]
This error is not showing always and never after the first load. After filtering the table for 5-6 time, I am having this error.
I am worried that if the mapping and the criteria is right or not. Any suggestion would be very helpful.
I think you need to provide an alias, so you should change your code this way:
Criteria criteria = getSessionFactory().getCurrentSession().createCriteria(Activity.class);
criteria.createCriteria("activityType", "at")
.add(
Restrictions.like("at.name", value.toString(), MatchMode.START));

Categories