How Hibernate to query three tables in a time? - java

I have three tables :
1. org,
2. product_info
3. service_info.
And, table product_info is mapping table service_info ManyToMany,
means,many products mapping many services.
While,table org is mapping table product_info OneToMany,
means,one org have many products.
When I initialize my web
I want to view the org table's column. How to do ?
Under classes are the persistent classes for three tables.
ProductService class:
`
#Entity
#Table(name="product_service")
#Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class ProductService implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String id;
private ServiceInfo serviceInfo;//this is the service table
private String parammapping;
private ProductInfo productInfo;//this is the product table
// Constructors
/** default constructor */
public ProductService() {
}
/** minimal constructor */
public ProductService(String id) {
this.id = id;
}
// Property accessors
#Id
#Column(name="ID", unique=true, nullable=false, length=50)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="SERVICEID")
public ServiceInfo getServiceInfo() {
return this.serviceInfo;
}
public void setServiceInfo(ServiceInfo serviceInfo) {
this.serviceInfo = serviceInfo;
}
#Column(name="PARAMMAPPING", length=1000)
public String getParammapping() {
return parammapping;
}
public void setParammapping(String parammapping) {
this.parammapping = parammapping;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="PRODUCTID")
public ProductInfo getProductInfo() {
return this.productInfo;
}
public void setProductInfo(ProductInfo productInfo) {
this.productInfo = productInfo;
}
}`
baseOrg class:
#Entity
#Table(name="base_org")
#Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class BaseOrg implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String code;
private String name;
private List<BaseRuleEngineLog> serviceUsedLogs = new ArrayList<BaseRuleEngineLog>(0);
private List<ProductInfo> productInfos = new ArrayList<ProductInfo>(0);
private List<BaseCreditQuery> baseCreditQueries = new ArrayList<BaseCreditQuery>(0);
// Constructors
/** default constructor */
public BaseOrg() {
}
/** minimal constructor */
public BaseOrg(String id) {
this.id = id;
}
#Id
#Column(name="ID", unique=true, nullable=false, length=50)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
#Column(name="CODE", length=50)
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
#Column(name="NAME", length=200)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="baseOrg")
public List<BaseRuleEngineLog> getServiceUsedLogs() {
return this.serviceUsedLogs;
}
public void setServiceUsedLogs(List<BaseRuleEngineLog> serviceUsedLogs) {
this.serviceUsedLogs = serviceUsedLogs;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="baseOrg")
public List<ProductInfo> getProductInfos() {
return this.productInfos;
}
public void setProductInfos(List<ProductInfo> productInfos) {
this.productInfos = productInfos;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="baseOrg")
public List<BaseCreditQuery> getBaseCreditQueries() {
return this.baseCreditQueries;
}
public void setBaseCreditQueries(List<BaseCreditQuery> baseCreditQueries) {
this.baseCreditQueries = baseCreditQueries;
}
}
productInfo class:
#Entity
#Table(name="product_info")
#Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
public class ProductInfo implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String id;
private BaseOrg baseOrg;//baseOrg table
private String code;
private String name;
private String orgcode;
private List<ProductService> productServices = new ArrayList<ProductService>(0);
// Constructors
/** default constructor */
public ProductInfo() {
}
/** minimal constructor */
public ProductInfo(String id) {
this.id = id;
}
// Property accessors
#Id
#Column(name="ID", unique=true, nullable=false, length=50)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="ORGID")
public BaseOrg getBaseOrg() {
return this.baseOrg;
}
public void setBaseOrg(BaseOrg baseOrg) {
this.baseOrg = baseOrg;
}
#Column(name="CODE", length=100)
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
#Column(name="NAME", length=100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="ORGCODE", length=100)
public String getOrgcode() {
return this.orgcode;
}
public void setOrgcode(String orgcode) {
this.orgcode = orgcode;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="productInfo")
public List<ProductService> getProductServices() {
return this.productServices;
}
public void setProductServices(List<ProductService> productServices) {
this.productServices = productServices;
}
}
serviceInfo class
#Entity
#Table(name="service_info")
#Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class ServiceInfo implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private String code;
private List<ProductService> productServices = new ArrayList<ProductService>(0);
// Constructors
/** default constructor */
public ServiceInfo() {
}
/** minimal constructor */
public ServiceInfo(String id) {
this.id = id;
}
// Property accessors
#Id
#Column(name="ID", unique=true, nullable=false, length=50)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
#Column(name="NAME", length=100)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="CODE", length=100)
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="serviceInfo")
public List<ProductService> getProductServices() {
return this.productServices;
}
public void setProductServices(List<ProductService> productServices) {
this.productServices = productServices;
}
}
product_service table
Thank you for forgiving my poor English,this is my first time questioning on Stack Overflow.

OK,I resolve it.
i found its so sample,lol.
Because,most criteria have been packaged.At the first time ,I want to use the HQL to resolve it,but in vain.I just add this sentences,and getted it.
enter image description here

Related

Hibernate. How to select child entities with a several parent fields with writing all it in parent entity

I have a next question: while working with Hibernate 3.3.0 run into a situation when I have two tables with one-to-many relationships and I need to get the list of parents. In each entity must be filled the several fields from the parent table and a list of all children mapped in the parent. For the easiest understanding, I give an example. I have two tables with one-to-many relationships: parent is "recipients" and child is "requisites". And I have two classes whose objects are the rows of these tables. Class for the table of recipients:
#Entity
#Table(name = "recipients")
#JsonFilter(value = "recipientsFilter")
public class POJORecipient implements POJO {
private static final long serialVersionUID = 4436819032452218525L;
#Id
#Column
private long id;
#Version
#Column
private long version;
#Column(name = "client_id")
private long clientId;
#Column
private String inn;
#Column
private String name;
#Column(name = "rcpt_country_code")
private String rcptCountryCode;
#Column(name = "rcpt_passp_ser")
private String rcptPasspSer;
#Column(name = "rcpt_passp_num")
private String rcptPasspNum;
#OneToMany(mappedBy = "recipient", fetch = FetchType.LAZY)
#JsonManagedReference
private Set<POJORequisite> requisites = new HashSet<>();
public POJORecipient(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public long getClientId() {
return clientId;
}
public void setClientId(long clientId) {
this.clientId = clientId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getInn() {
return inn;
}
public void setInn(String inn) {
this.inn = inn;
}
public String getRcptCountryCode() {
return rcptCountryCode;
}
public void setRcptCountryCode(String rcptCountryCode) {
this.rcptCountryCode = rcptCountryCode;
}
public String getRcptPasspSer() {
return rcptPasspSer;
}
public void setRcptPasspSer(String rcptPasspSer) {
this.rcptPasspSer = rcptPasspSer;
}
public String getRcptPasspNum() {
return rcptPasspNum;
}
public void setRcptPasspNum(String rcptPasspNum) {
this.rcptPasspNum = rcptPasspNum;
}
public Set<POJORequisite> getRequisites() {
return requisites;
}
public void setRequisites(Set<POJORequisite> requisites) {
this.requisites = requisites;
}
}
and for requisites table:
#Entity
#Table(name = "requisites")
public class POJORequisite implements POJO {
private static final long serialVersionUID = -35864567359179960L;
#Id
#Column
private long id;
#Version
#Column
private long version;
#Column
private String bic;
#Column
private String bill;
#Column
private String comments;
#Column
private String note;
#ManyToOne
#JoinColumn(name = "recipient_id")
#JsonBackReference
private POJORecipient recipient;
public POJORequisite(){}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public String getBic() {
return bic;
}
public void setBic(String bic) {
this.bic = bic;
}
public String getBill() {
return bill;
}
public void setBill(String bill) {
this.bill = bill;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public POJORecipient getRecipient() {
return recipient;
}
public void setRecipient(POJORecipient recipient) {
this.recipient = recipient;
}
}
So, I want to select from the recipients only names and all mapped requisites. Consequently, after the selection, I will have a list of POJORecipient objects and in each object filled only the field "name" and set of POJORequisite objects.
As answer of my question I want to discover one of next: how can I do that with help HQL or Criteria API (the second variant is preferable), or understand it is impossible in Hibernate at all, or that this possibility appeared in later versions (also preferably with example). I'm trying to resolve this question for several months now and will be immensely grateful for any help. All clarifications and advices also will be so helpful. Thanks in advance!!!

How to resolve java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer in Spring

MenuModel
#Entity
#Table(name="M_MENU", uniqueConstraints={#UniqueConstraint(columnNames={"NAME"})})
public class MenuModel {
private Integer id;
private String code;
private String name;
private String controller;
private Integer parent_id;
#Id
#Column(name="ID")
#GeneratedValue(strategy=GenerationType.TABLE, generator="M_MENU")
#TableGenerator(name="M_MENU", table="M_SEQUENCE",
pkColumnName="SEQUENCE_NAME", pkColumnValue="M_MENU_ID",
valueColumnName="SEQUENCE_VALUE", allocationSize=1, initialValue=0
)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name="CODE")
public String getCode() {
return code;
}
public void setCode(String kode) {
this.code = kode;
}
#Column(name="NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="CONTROLLER")
public String getController() {
return controller;
}
public void setController(String controller) {
this.controller = controller;
}
#Column(name="PARENT_ID")
public Integer getParent_id() {
return parent_id;
}
public void setParent_id(Integer parent_id) {
this.parent_id = parent_id;
}
}
UserAccessModel
#Entity
#Table(name="M_USER_ACCESS")
public class UserAccessModel {
private Integer id;
//join table role
private Integer idRole;
private RoleModel roleModel;
//join table menu
private Integer idMenu;
private MenuModel menuModel;
#Id
#Column(name="ID")
#GeneratedValue(strategy=GenerationType.TABLE, generator="M_USER_ACCESS")
#TableGenerator(name="M_USER_ACCESS", table="M_SEQUENCE",
pkColumnName="SEQUENCE_NAME", pkColumnValue="M_USER_ACCESS_ID",
valueColumnName="SEQUENCE_VALUE", allocationSize=1, initialValue=0
)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name="ID_ROLE")
public Integer getIdRole() {
return idRole;
}
public void setIdRole(Integer idRole) {
this.idRole = idRole;
}
#ManyToOne
#JoinColumn(name="ID_ROLE", nullable=true, updatable=false, insertable=false)
public RoleModel getRoleModel() {
return roleModel;
}
public void setRoleModel(RoleModel roleModel) {
this.roleModel = roleModel;
}
#Column(name="ID_MENU")
public Integer getIdMenu() {
return idMenu;
}
public void setIdMenu(Integer idMenu) {
this.idMenu = idMenu;
}
#ManyToOne
#JoinColumn(name="ID_MENU", nullable=true, updatable=false, insertable=false)
public MenuModel getMenuModel() {
return menuModel;
}
public void setMenuModel(MenuModel menuModel) {
this.menuModel = menuModel;
}
}
MenuDaoImpl
#Override
public List<MenuModel> searchByRole(Integer idRole) {
// TODO Auto-generated method stub
Session session = this.sessionFactory.getCurrentSession();
List<MenuModel> menuModelListRole = new ArrayList<MenuModel>();
Criteria userAccessCriteria = session.createCriteria(UserAccessModel.class,"UA");
Criteria menuCriteria = userAccessCriteria.createCriteria("menuModel","M");
userAccessCriteria.add(Restrictions.eq("idRole", ""+idRole+""));
ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("M.id"));
properties.add(Projections.property("M.name"));
properties.add(Projections.property("M.code"));
properties.add(Projections.property("M.controller"));
properties.add(Projections.property("M.parent_id"));
menuCriteria.setProjection(properties);
menuModelListRole = menuCriteria.list();
return menuModelListRole;
}
I want to get result of the following sql:
select M.ID ID, M.NAME NAME, M.CODE CODE, M.CONTROLLER CONTROLLER,
M.PARENT_ID PARENT from M_MENU M join M_USER_ACCESS UA on UA.ID_MENU
= M.ID where UA.ID_ROLE="+idRole+"
I got error in method searchByRole in menuModelListRole = menuCriteria.list();. How can i resolve the problem?
Here private Integer idRole; is of Integer type, but you are passing idRole as String in Restrictions.eq("idRole", ""+idRole+""). SO you are getting java.lang.String cannot be cast to java.lang.Integer in Spring
Changing you restriction value from Restrictions.eq("idRole", ""+idRole+"") to Restrictions.eq("idRole", idRole) should solve your problem.

Spring boot jpa/hibernate tables connection

professionals!
I have a question. What is a better idea to connect 2 tables in spring boot via ID? As an example: we have 2 tables client and books. Each client can borrow a book and the status of book will be changed.
I know how to make it in DB using SQL. But the question is, how to do this in jpa/hibernate.
I have an error of ManyToMany or OneToMany.....
#Entity
public class Book implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(name = "BOOK_GEN", allocationSize = 1)
#Id
#GeneratedValue(generator = "BOOK_GEN")
private int id;
private String book_name;
private String ISBN;
private String publish_year;
private String publisher;
private Boolean status;
#OneToMany(mappedBy="book" ,cascade=CascadeType.ALL , fetch = FetchType.LAZY)
private Collection<Client> authors =new ArrayList<Client>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBook_name() {
return book_name;
}
public void setBook_name(String book_name) {
this.book_name = book_name;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public String getPublish_year() {
return publish_year;
}
public void setPublish_year(String publish_year) {
this.publish_year = publish_year;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Collection<Author> getAuthors() {
return authors;
}
public void setClients(Collection<Client> clients) {
this.clients = clients;
}}
#Entity
public class Client implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(name = "CLT_GEN", allocationSize = 1)
#Id
#GeneratedValue(generator = "CLT_GEN")
private int id;
private Boolean bookedstatus;
private Boolean bookstatus;
#ManyToOne(fetch = FetchType.LAZY)
private Book book;
private String name ;
private String surname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Boolean getBookedstatus() {
return bookedstatus;
}
public void setBookedstatus(Boolean bookedstatus) {
this.bookedstatus = bookedstatus;
}
public Boolean getBookstatus() {
return bookstatus;
}
public void setBookstatus(Boolean bookstatus) {
this.bookstatus = bookstatus;
}
}
Since you have mentioned "A client can borrow a book", one-to-one mapping should work the best for you. Please refer to the below code. Also you didn't mention the error you are facing with your current implementation.
#Entity
public class Book implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(name = "BOOK_GEN", allocationSize = 1)
#Id
#GeneratedValue(generator = "BOOK_GEN")
private int id;
private String book_name;
private String ISBN;
private String publish_year;
private String publisher;
private Boolean status;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "book", cascade = CascadeType.ALL)
private Collection<Client> authors;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBook_name() {
return book_name;
}
public void setBook_name(String book_name) {
this.book_name = book_name;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public String getPublish_year() {
return publish_year;
}
public void setPublish_year(String publish_year) {
this.publish_year = publish_year;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Collection<Client> getAuthors() {
return authors;
}
public void setAuthors(Collection<Client> authors) {
this.authors = authors;
}
}
#Entity
public class Client implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(name = "CLT_GEN", allocationSize = 1)
#Id
#GeneratedValue(generator = "CLT_GEN")
private int id;
private Boolean bookedstatus;
private Boolean bookstatus;
#OneToOne(fetch = FetchType.LAZY)
#PrimaryKeyJoinColumn
private Book book;
private String name ;
private String surname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Boolean getBookedstatus() {
return bookedstatus;
}
public void setBookedstatus(Boolean bookedstatus) {
this.bookedstatus = bookedstatus;
}
public Boolean getBookstatus() {
return bookstatus;
}
public void setBookstatus(Boolean bookstatus) {
this.bookstatus = bookstatus;
}
}

child not detach from parent

My document entity class is
#Entity
#Table(name="Document_Directory")
public class DocumentDirectoryEntity{
private int id;
private String name;
private DocumentDirectoryEntity parentDirectory;
private List<DocumentDirectoryEntity> childDirectoryList;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Column(name="name", length=250, nullable= false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="parent_dir_id")
public DocumentDirectoryEntity getParentDirectory() {
return parentDirectory;
}
public void setParentDirectory(DocumentDirectoryEntity parentDirectory) {
this.parentDirectory = parentDirectory;
}
#OneToMany(mappedBy="parentDirectory", cascade=CascadeType.ALL, fetch=FetchType.LAZY, orphanRemoval=true)
public List<DocumentDirectoryEntity> getChildDirectoryList() {
return childDirectoryList;
}
public void setChildDirectoryList(List<DocumentDirectoryEntity> childDirectoryList) {
this.childDirectoryList = childDirectoryList;
}
}
I want delete a document but before delete, i want to change its child's parent. But I am not able to do it. code is:-
DocumentDirectoryEntity documentDirectoryEntity = documentDirectoryDao.findById(1);
DocumentDirectoryEntity documentDirectoryEntity1 = documentDirectoryDao.findById(2);
List<DocumentDirectoryEntity> childDirectoryList = documentDirectoryEntity.getChildDirectoryList();
DocumentDirectoryEntity childDirectory = childDirectoryList.get(0);
childDirectory.setParentDirectory(documentDirectoryEntity1);
documentDirectoryDao.update(childDirectory);
documentDirectoryDao.delete(documentDirectoryEntity);
when i delete object documentDirectoryEntity then childDirectory row is also removed.

Can not set int field com.java.hibernate.practise.User.id to java.util.HashSet

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;
}

Categories

Resources