I have the following classes
// COMPANY
#Entity
#Table(name=Company.TABLE_NAME)
public class Company {
public static final String TABLE_NAME = "company";
public static final String PK_NAME = "id";
#Id
#Column(name="id")
private String id = IdGenerator.createId();
#ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER)
#JoinColumn(name="categoryid", table=TABLE_NAME)
private Category category;
#Column(name = "name", nullable=false, table=TABLE_NAME)
#Size(min=2, max=60, message="LATER")
private String name;
#Column(name="domainName", nullable=true, table=TABLE_NAME)
private String domainName;
#Column(name="registrationNumber", nullable=true, table=TABLE_NAME)
private String registrationNumber;
#Column(name="description", table=TABLE_NAME)
private String description;
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
#JoinColumn(name="itemId")
private Set<Image> logos = new HashSet<>();
#OneToMany(mappedBy="company", cascade=CascadeType.ALL, fetch=FetchType.LAZY)
private List<Branch> branches = new ArrayList<>();
public Company() {}
public void addBranch(Branch branch) {
branch.setCompany(this);
branch.getAddress().setActor(this);
branches.add(branch);
}
public void addLogo(Image logo) {
}
// GETTERS AND SETTERS
}
// BRANCHES
#Entity
#Table(name=Branch.TABLE_NAME)
public class Branch {
public static final String TABLE_NAME = "branch";
#Id
#Column(name = "id")
private String id = IdGenerator.createId();
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="address")
private Address address;
#Column(name = "telephone")
private String telephone;
#ManyToOne
#JoinColumn(name="company")
private Company company;
public Branch() {
this.address.setAddressCategory(AddressCategory.BRANCH);
}
// GETTERS AND SETTERS
}
// ADDRESS
#Entity
#Table(name=Address.TABLE_ADDRESS)
public class Address {
public static final String TABLE_ADDRESS = "address";
#Id
#Column(name="id")
private String id = IdGenerator.createId();
#Column(name="category", nullable=false)
private AddressCategory addressCategory;;
#Column(name="streetname", nullable=true)
private String streetname;
#Column(name="number", nullable=true)
private String number;
#Column(name="postcode", nullable=true)
private String postcode;
#Column(name="city", nullable=true)
private String city;
#Column(name="country", nullable=true)
private String country;
#Column(name = "telephone")
private String telephone;
#Embedded
private EmailAddress email;
#Column(name="description", nullable=true)
private String description;
// GETTERS AND SETTERS
}
// EMAIL
#Embeddable
public class EmailAddress {
#Column(name="email")
private String emailAddress;
public EmailAddress() { }
public EmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
public String getEmailAddress() { return emailAddress; }
public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; }
}
// COMPANY DTO
public class CompanyDTO {
private String id;
private String categoryId;
private String name;
private String domainName;
private String registrationNumber;
private String description;
private List<Branch> branches = new ArrayList<>();
public CompanyDTO fromCompany(Company company) {
this.setId(company.getId());
this.setName(company.getName());
this.setDomainName(company.getDomainName());
this.setRegistrationNumber(company.getRegistrationNumber());
this.setDescription(company.getDescription());
return this;
}
public Company toCompany(Company company) {
company.setName(getName());
company.setDomainName(getDomainName());
company.setRegistrationNumber(getRegistrationNumber());
company.setDescription(getDescription());
//company.setLogo(new Image());
company.setBranches(this.getBranches());
return company;
}
// GETTERS AND SETTERS
}
The controller method:
#PostMapping(path = CREATE_COMPANY)
public ResponseEntity<?> save(#RequestBody CompanyDTO dto){ System.out.println("__________COMPANY----------");
Category category = categoryService.findById(dto.getCategoryId());
Company company = dto.toCompany(new Company());
company.setCategory(category);
company.setLogos(new HashSet<Image>(Arrays.asList(new Image("garden", "garden.jpg", "/garden"))));
companyService.save(company);
return new ResponseEntity<> ("", HttpStatus.CREATED);
}
This is the JSON I am sending from Postman:
{
"categoryId": "ee6e75c9-2d1b-41c1-8f12-236fbf907683",
"name": "McDonalds",
"domainName": "Vodafone.com",
"registrationNumber": "5555555",
"description": "Vodafone",
"branches": [
{
"telephone": "003325647895",
"address": {
"addressCategory": "BRANCH",
"streetname": "Milkweg",
"number": "50",
"postcode": "3014",
"city": "Vienna",
"country": "Austria",
"email": {"email": "example#mail.com"},
"telephone": "003325647895",
"description": "P. O. Box decription",
"actor": "1abaaa11-1145-432f-84b0-40b9b551acdd"
}
}
],
"logos": []
}
And I get the following error in Postman: 400 Bad Request. It is even never sent to the server because it is a bad request.
If I remove the object inside the array branches attribute (empty array), then it works.
I have double check my attributes names but everything seems to be correct. I just don't know what is wrong.
Related
#Entity
#Table(name = "users")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(nullable = false, unique = true)
private Long id;
private String firstName;
private String lastName;
private String email;
private String password;
#OneToOne(fetch = FetchType.LAZY,
cascade = CascadeType.ALL,
mappedBy = "user")
private UserProfile userProfile;
// Hibernate requires a no-arg constructor
public User() {
}
public User(String firstName, String lastName, String email, String password) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.password = password;
}
// Getters and Setters (Omitted for brevity)
}
UserProfile
#Entity
#Table(name = "user_profiles")
public class UserProfile implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String phoneNumber;
private String gender;
private String address1;
private String address2;
private String street;
private String city;
private String state;
private String country;
private String zipCode;
#OneToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "user_id", nullable = false)
private User user;
public UserProfile() {
}
public UserProfile(String phoneNumber, String gender,
String address1, String address2, String street, String city,
String state, String country, String zipCode) {
this.phoneNumber = phoneNumber;
this.gender = gender;
this.address1 = address1;
this.address2 = address2;
this.street = street;
this.city = city;
this.state = state;
this.country = country;
this.zipCode = zipCode;
}
// Getters and Setters (Omitted for brevity)
}
My Service
#Component
public class UserService {
#Autowired
UserRepo userRepo;
public ResponseEntity<User> createUser(String firstName, String lastName, String email, String password){
User user=new User(firstName,lastName,email,password);
return new ResponseEntity<>(user,HttpStatus.OK);
}
public ResponseEntity<List<User>> savedataBase(User user){
userRepo.save(user);
return new ResponseEntity<>( userRepo.findAll(), HttpStatus.OK);
}
}
#Component
public class UserPServer {
#Autowired
UserProfileRepo userProfileRepo;
public ResponseEntity<List<UserProfile>> save(UserProfile userProfile){
userProfileRepo.save(userProfile);
return new ResponseEntity<>( userProfileRepo.findAll(), HttpStatus.OK);
}
}
My Controller
#RestController
#RequestMapping("/user")
public class UserController {
#Autowired
UserService userService;
#GetMapping("/create/{firsName}/{lastName}/{email}/{password}")
public ResponseEntity<User> create(#PathVariable("firsName") String firstName,
#PathVariable("lastName") String lastName,
#PathVariable("email") String email,
#PathVariable("password") String password){
return userService.createUser(firstName,lastName,email,password);
}
#PostMapping("/usersave")
public ResponseEntity<List<User>> saveDateBase(#RequestBody User users){
return userService.savedataBase(users);
}
}
#RestController
#RequestMapping("/userprofile")
public class UserPConroller {
#Autowired
UserPServer userPServer;
#PostMapping("/userpsave")
public ResponseEntity<List<UserProfile>> savep(UserProfile userProfile){
return userPServer.save(userProfile);
}
}
UserProfile classes like above
I get error like this:
*Column 'user_id' cannot be null
2019-12-26 11:27:35.618 ERROR 6540 --- [nio-8883-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
edit your application.properties file like this
spring.jpa.hibernate.ddl-auto = update
Once you decided who is the "parent" in this relationship you should save the child first with its repository.
Lets assume it is the User.
You would do something like this in your controller
UserProfile newUser = user.getUserProfile();
userProfileRepository.save(newUser);
userRepository.save(user);
This guarantee garantee that the relation is successful.
I am trying to save a list of directors of a company whenever i create a new merchant, thus i have a #ManyToOne relationship between Director and Merchant respectively.
Thus far i have managed to get it to save the list of directors and the merchant when i do a POST. However when i do a GET request i do not get back the directors, the list comes back empty. When i check in the database, the joining column is empty as shown in the image but the rest of the data is present. How can i solve this issue?
This is my code :
Director.java
#Entity
#Table(name = "Directors")
public class Director {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long directorID;
#Cascade({org.hibernate.annotations.CascadeType.ALL})
#ManyToOne
#JoinColumn(name = "merchantNumber")
private Merchant merchant;
#NotBlank
private String name;
#NotBlank
private String surname;
public Director() {
}
public Director(long directorID, Merchant merchant, String name, String surname) {
this.directorID = directorID;
this.merchant = merchant;
this.name = name;
this.surname = surname;
}
...
Getters and setters
DirectorRepository.java
public interface DirectorRepository extends CrudRepository<Director, String> {
}
Merchant.java
public class Merchant {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int merchantNumber;
#NotBlank
private String merchantID;
#NotBlank
private String businessName;
#Cascade({org.hibernate.annotations.CascadeType.ALL})
#OneToMany(mappedBy = "merchant")
private List<Director> directors;
#NotBlank
private String userName;
public Merchant(int merchantNumber, String merchantID, String businessName, List<Director> directors, String userName ) {
this.merchantNumber = merchantNumber;
this.merchantID = merchantID;
this.businessName = businessName;
this.directors = directors;
this.userName = userName;
}
...
Getter and setters
MerchantService.java
public ResponseMerchantQuery createMerchant(Merchant merchant) {
if( merchant == null || merchant.getMerchantID()== null){
throw new ResourceNotFoundException("Empty", "Missing Data Exception");
} else {
merchant.setPassword(passwordEncoder.encode(merchant.getPassword()));
merchantRepository.save(merchant);
String merchantNum = Long.toString(merchant.getMerchantNumber());
return new ResponseMerchantQuery(merchantNum, "Merchant Created Successfully");
}
}
MerchantController.java
#RequestMapping(method = RequestMethod.POST, value = "/api/merchants")
public ResponseMerchantQuery createMerchant(#Valid #RequestBody Merchant merchant){
System.out.println("size of merchnat " + merchant.getDirectors().size());
return merchantService.createMerchant(merchant);
}
So first a bit of back story. The issue I am having is when I create a user. Previously I had tried to create a user and assign them a role separately before discovering that by inserting into the SEC_USER_ROLE table the program was also inserting into the APP_USER table and I was getting an error about inserting duplicate values into the parent table. However, now by creating the user and role together I am getting the following error:
Primary key should be primitive (or list of primitives for composite
pk) , an instance of java.lang.Long with the primary keys filled in or
an instance of WebIntSecRole.......
Code as follows, not sure where I'm goin g wrong or the best solution at this point.
Admin.java:
//New User Creation
WebIntUser newUser = new WebIntUser();
newUser.setLoginId(newLoginName);
newUser.setCreatedBy(loggedUser);
newUser.setCreatedOn(today);
newUser.setDbAuth(true);
newUser.setDeleted(false);
newUser.setDisabled(false);
newUser.setEmail(newEmail);
newUser.setEncrypted(true);
newUser.setEncryptPassword(true);
newUser.setFirstName(newFirstName);
newUser.setLastName(newLastName);
newUser.setUpdatedBy(loggedUser);
newUser.setUpdatedOn(today);
newUser.setVersion(1);
newUser.setLdapId(1);
//userService.createUser(newUser);
//Set role for new user
WebIntSecRoleUser newUserRole = new WebIntSecRoleUser();
newUserRole.setUser(newUser);
newUserRole.setDeleted(false);
newUserRole.setRole(userService.selectRoleById(1));
//newUserRole.setCreatedBy(loggedUser);
//newUserRole.setCreatedOn(today);
//newUserRole.setUpdatedBy(loggedUser);
//newUserRole.setUpdatedOn(today);
newUserRole.setVersionNumber(0);
userService.createRole(newUserRole);
WebIntUser.java
#Entity
#Table(name = "APP_USER")
#EntityListeners(value = { AuditChangeListener.class })
public class WebIntUser implements Serializable {
public WebIntUser() {
};
public WebIntUser(String login, String pass) {
this.loginId = login;
this.password = pass;
}
private Integer userId;
private String loginId;
private String password;
private String firstName;
private String lastName;
private String email;
private boolean disabled;
private boolean deleted;
private boolean dbAuth;
private boolean isEncrypted;
private boolean encryptPassword;
private Date lastLogin;
private Date prevLogin;
private Integer version;
private Date lastPasswordChange;
private Date createdOn;
private Date updatedOn;
private String createdBy;
private String updatedBy;
private Integer ldapId;
public static interface propertyName {
String userId = "userId";
String loginId = "loginId";
String password = "password";
String firstName = "firstName";
String lastName = "lastName";
String email = "email";
String disabled = "disabled";
String deleted = "deleted";
String dbAuth = "dbAuth";
String isEncrypted = "isEncrypted";
String encryptPassword = "encryptPassword";
String lastLogin = "lastLogin";
String prevLogin = "prevLogin";
String version = "version";
String lastPasswordChange = "lastPasswordChange";
String createdOn = "createdOn";
String updatedOn = "updatedOn";
String createdBy = "createdBy";
String updatedBy = "updatedBy";
String ldapId = "ldapId";
}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "USER_ID", nullable = false)
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
.....getters/setters
}
WebIntSecRoleUser.java:
#Entity
#Table(name = "SEC_ROLE_USER")
#EntityListeners(value = {AuditInfoChangeListener.class})
public class WebIntSecRoleUser implements AuditableDomainObject {
private Long id;
private WebIntSecRole role;
private WebIntUser user;
private boolean deleted;
private AuditInfo auditInfo;
private long versionNumber;
private Date createdOn;
private Date updatedOn;
private String createdBy;
private String updatedBy;
public interface propertyName extends Auditable.propertyName {
String id="id";
String role="role";
String user="user";
String deleted = "deleted";
String createdOn = "createdOn";
String updatedOn = "updatedOn";
String createdBy = "createdBy";
String updatedBy = "updatedBy";
}
public static interface permissionKey{
String UPDATE="SecRoleUser.U";
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "ROLE_USER_ID",nullable = false, unique = true)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#JoinColumn(name="ROLE_ID", nullable=false)
public WebIntSecRole getRole() {
return role;
}
public void setRole(WebIntSecRole role) {
this.role = role;
}
#ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name="USER_ID", nullable = false)
public WebIntUser getUser() {
return user;
}
public void setUser(WebIntUser user) {
this.user = user;
}
Getters/setters
}
Note: There is some commented out code that I'm either trying not to use anymore, or in the case of Created By and Created On etc I was getting errors for multiple inserts.
In my opinion you have missed the #ManyToOne mapping on the WebIntSecRole. You only specified the #JoinColumn.
#ManyToOne(/* desired options */)
#JoinColumn(name="ROLE_ID", nullable=false)
public WebIntSecRole getRole() {
return role;
I am using Hibernate with Spring in my project, I want to write a HQL query to get and update the role of user. How can I do that
This is my ERD:
this is my java classes:
User
#Entity
#Table(name = "users")
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "userId")
private int userId;
#Column(name = "userIdCardNo")
private String useridcardno;
#Column(name = "userFname")
private String fname;
#Column(name = "userMname")
private String mname;
#Column(name = "userLname")
private String lname;
#Column(name = "userPhone")
private int phone;
#Column(name = "userPhone2")
private String phone2;
#Column(name = "userAddress")
private String address;
#Column(name = "userAddress2")
private String address2;
#Column(name = "userName")
private String username;
#Column(name = "userPass")
private String password;
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "users_roles", joinColumns = #JoinColumn(name = "userId", nullable = false) , inverseJoinColumns = #JoinColumn(name = "roleId", nullable = false) )
private List<Role> roles;
#Enumerated(EnumType.STRING)
#Column(name = "userStatus")
private UserStatus status;
//CREATE MD5 from String
public static String md5(String input) {
String md5 = null;
if (null == input)
return null;
try {
// Create MessageDigest object for MD5
MessageDigest digest = MessageDigest.getInstance("MD5");
// Update input string in message digest
digest.update(input.getBytes(), 0, input.length());
// Converts message digest value in base 16 (hex)
md5 = new BigInteger(1, digest.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return md5;
}
//CONTRUSCTORS
public User() {
}
public User(int userId, String useridcardno, String fname, String mname, String lname, int phone, String phone2,
String address, String address2, String username, String password, List<Role> roles, UserStatus status) {
super();
this.userId = userId;
this.useridcardno = useridcardno;
this.fname = fname;
this.mname = mname;
this.lname = lname;
this.phone = phone;
this.phone2 = phone2;
this.address = address;
this.address2 = address2;
this.username = username;
this.password = BCrypt.hashpw(password, BCrypt.gensalt());
this.roles = roles;
this.status = status;
}
//GETTERS and SETTERS
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUseridcardno() {
return useridcardno;
}
public void setUseridcardno(String useridcardno) {
this.useridcardno = useridcardno;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public int getPhone() {
return phone;
}
public void setPhone(int phone) {
this.phone = phone;
}
public String getPhone2() {
return phone2;
}
public void setPhone2(String phone2) {
this.phone2 = phone2;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public UserStatus getStatus() {
return status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
}
Role
#Entity
#Table(name = "roles")
public class Role {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "roleId")
private int id;
#Column(name = "roleName")
private String roleName;
#ManyToMany(fetch = FetchType.EAGER, mappedBy = "roles")
private List<User> users;
public Role() {
}
public Role(int id, String roleName, List<User> users) {
super();
this.id = id;
this.roleName = roleName;
this.users = users;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
And UsersRoles
#Entity
#Table(name="users_roles")
public class UsersRoles {
#Id
#Column(name="userId")
private int userId;
#Id
#Column(name="roleId")
private int roleId;
public UsersRoles() {
}
public UsersRoles(int userId, int roleId) {
super();
this.userId = userId;
this.roleId = roleId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getRoleId() {
return roleId;
}
public void setRoleId(int roleId) {
this.roleId = roleId;
}
}
I'm quite new to database queries since I have tried with for only a few times. I can get the data in one table, but for joining tables like this, I really need a hint.
Just load the user and modifiy the items of the role list. Then commit the transaction. - That's all.
EntityManager em ...
...
<begin Transaction>
...
User user = em.find(User.class, 1); //load by id 1 - just for example
User role1 = em.find(Role.class, 1); //load by id 1 - just for example
user.getRoles().add(role1);
...
<commit Transaction>
It is so simple because you use an ORM (Object Relational Mapper)(Hibernate). I almost all cases there is no need to write queries for updates, instead the state of the objects gets persisted.
I have hibernate #OneToMany mapping I am getting the mentioned error. Does not understand the reason. As getters and setters are public
Below are the entities
#Entity
#Table(name="USER_DETAILS")
public class User implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name="USER_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name="USER_FIRSTNAME",nullable=false, length=50)
private String userFirstName;
#Column(name="USER_LASTNAME",nullable=false, length=50)
private String userLastName;
#Column(name="USER_MIDDLENAME",length = 30)
private String userMiddleName;
#Column(name="USER_AGE")
private int userAge;
#Column(name="USER_SEX")
private String userSex;
#OneToMany(cascade=CascadeType.ALL, mappedBy="userAddress", targetEntity=Address.class)
private Set<Address> address = new HashSet<Address>();
public String getUserFirstName() {
return userFirstName;
}
public void setUserFirstName(String userFirstName) {
this.userFirstName = userFirstName;
}
public String getUserLastName() {
return userLastName;
}
public void setUserLastName(String userLastName) {
this.userLastName = userLastName;
}
public String getUserMiddleName() {
return userMiddleName;
}
public void setUserMiddleName(String userMiddleName) {
this.userMiddleName = userMiddleName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public String getUserSex() {
return userSex;
}
public void setUserSex(String userSex) {
this.userSex = userSex;
}
public Set<Address> getAddress() {
return address;
}
public void setAddress(Set<Address> address) {
this.address = address;
}
}
#Entity
#Table(name = "ADDRESS")
public class Address implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#Column(name = "ADDRESS_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column(name = "ZIP_CODE")
private String zipCode;
#Column(name="ADDRESS_USER_ID", insertable=false, updatable=false)
private Long addressUserID;
#Column(name = "ADDRESS_SEC")
private String addressSec;
#Column(name = "STREET")
private String street;
#Column(name = "CITY")
private String city;
#Column(name = "COUNTRY")
private String country;
#ManyToOne(cascade=CascadeType.ALL, targetEntity=User.class)
#JoinColumn(name="ADDRESS_USER_ID")
private Set<User> userAddress = new HashSet<User>();
public Long getAddressUserID() {
return addressUserID;
}
public void setAddressUserID(Long addressUserID) {
this.addressUserID = addressUserID;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public Set<User> getUserAddress() {
return userAddress;
}
public void setUserAddress(Set<User> userAddress) {
this.userAddress = userAddress;
}
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 getAddressSec() {
return addressSec;
}
public void setAddressSec(String addressSec) {
this.addressSec = addressSec;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
Part of Stack Trace are:
Exception in thread "main" org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.java.hibernate.practise.User.id at... org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:62)
Caused by: java.lang.IllegalArgumentException: Can not set int field com.java.hibernate.practise.User.id to java.util.HashSet...
I am generating the schema using hibernate.hbm2ddl.auto= cerate-drop
Please guide on this.
Generally when we use 1..n bidirectional entity mapping, the owning side which is in general, the many side, should have only a single instance reference to the one side object (not a collection - that would be many to many), and the join column to use is the primary key from the on side class. We don't need to explicitly use the FK column in the many side like you are.
So if this is your relationship User [1]..[N] Address, then you should have something more like
public class User {
...
#OneToMany(mappedBy = "user", cascade=CascadeType.ALL)
private Set<Address> addresses;
}
public class Address {
// private Long addressUserID; // Don't need this property. We get it below
...
#ManyToOne
#JoinColumn(name = "USER_ID")
private User user;
}