I having problems saving many to many relationships to a pivot table.
The way the pojos are created is unfortunately a pretty long process which spans over a couple of different threads which work on the (to this point un-saved) object until it is finally persisted. I associate the related objects to one another right after they are created and when debugging I can see the List of related object populated with their respective objects. So basically all is fine to this point. When I persist the object everything get saved except the relations in the pivot table.
mapping files:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.thebeansgroup.jwinston.plugin.orm.hibernate.object">
<class name="ShowObject" table="show_object">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
<set cascade="all" inverse="true" name="venues" table="venue_show">
<key column="show_id"/>
<many-to-many class="VenueObject"/>
</set>
</class>
</hibernate-mapping>
and the other
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.thebeansgroup.jwinston.plugin.orm.hibernate.object">
<class name="VenueObject" table="venue_object">
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
<property name="latitude" type="integer"/>
<property name="longitude" type="integer"/>
<set cascade="all" inverse="true" name="shows" table="venue_show">
<key column="venue_id"/>
<many-to-many class="ShowObject"/>
</set>
</class>
</hibernate-mapping>
pojos:
public class ShowObject extends OrmObject
{
private Long id;
private String name;
private Set venues;
public ShowObject()
{
}
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Set getVenues()
{
return venues;
}
public void setVenues(Set venues)
{
this.venues = venues;
}
}
and the other:
public class VenueObject extends OrmObject
{
private Long id;
private String name;
private int latitude;
private int longitude;
private Set shows = new HashSet();
public VenueObject()
{
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public int getLatitude()
{
return latitude;
}
public void setLatitude(int latitude)
{
this.latitude = latitude;
}
public int getLongitude()
{
return longitude;
}
public void setLongitude(int longitude)
{
this.longitude = longitude;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public Set getShows()
{
return shows;
}
public void setShows(Set shows)
{
this.shows = shows;
}
}
Might the problem be related to the lack of annotations?
Couple things to try:
You have inverse="true" on both ends of many-to-many. It should be only at one end.
Make your sets not lazy.
You didn't specify column property for many-to-many tag.
So it should look something like this at the end:
<class name="ShowObject" table="show_object">
...
<set lazy="false" cascade="all" name="venues" table="venue_show">
<key column="show_id"/>
<many-to-many class="VenueObject" column="venue_id" />
</set>
</class>
<class name="VenueObject" table="venue_object">
...
<set lazy="false" cascade="all" inverse="true" name="shows" table="venue_show">
<key column="venue_id"/>
<many-to-many class="ShowObject" column="show_id"/>
</set>
</class>
Related
I am trying to write a HQL Query, which is similar to a MySQL Join. Below are my entities. As you can see below I am not using annotations in my Pojos. Instead I am using XML to do the mapping.
Stock
public class Stock implements java.io.Serializable {
private Integer idstock;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private Product product;
private int quantity;
private Date dateCreated;
private Date lastUpdated;
public Stock() {
}
public Stock(Product product, int quantity) {
this.product = product;
this.quantity = quantity;
}
public Stock(Product product, int quantity, Date dateCreated, Date lastUpdated) {
this.product = product;
this.quantity = quantity;
this.dateCreated = dateCreated;
this.lastUpdated = lastUpdated;
}
public Integer getIdstock() {
return this.idstock;
}
public void setIdstock(Integer idstock) {
this.idstock = idstock;
}
public Product getProduct() {
return this.product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getQuantity() {
return this.quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getLastUpdated() {
return this.lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
}
Product
public class Product implements java.io.Serializable {
private Integer idproduct;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private SparePart sparePart;
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
private VehicleModel vehicleModel;
private double unitPrice;
private String qrcode;
private boolean enable;
private Integer minimumStockLevel;
private Integer stockReorderLevel;
public Product() {
}
public Product(SparePart sparePart, VehicleModel vehicleModel, double unitPrice, String qrcode, boolean enable) {
this.sparePart = sparePart;
this.vehicleModel = vehicleModel;
this.unitPrice = unitPrice;
this.qrcode = qrcode;
this.enable = enable;
}
public Product(SparePart sparePart, VehicleModel vehicleModel, double unitPrice, String qrcode, boolean enable, Integer minimumStockLevel, Integer stockReorderLevel) {
this.sparePart = sparePart;
this.vehicleModel = vehicleModel;
this.unitPrice = unitPrice;
this.qrcode = qrcode;
this.enable = enable;
this.minimumStockLevel = minimumStockLevel;
this.stockReorderLevel = stockReorderLevel;
}
public Integer getIdproduct() {
return this.idproduct;
}
public void setIdproduct(Integer idproduct) {
this.idproduct = idproduct;
}
public SparePart getSparePart() {
return this.sparePart;
}
public void setSparePart(SparePart sparePart) {
this.sparePart = sparePart;
}
public VehicleModel getVehicleModel() {
return this.vehicleModel;
}
public void setVehicleModel(VehicleModel vehicleModel) {
this.vehicleModel = vehicleModel;
}
public double getUnitPrice() {
return this.unitPrice;
}
public void setUnitPrice(double unitPrice) {
this.unitPrice = unitPrice;
}
public String getQrcode() {
return this.qrcode;
}
public void setQrcode(String qrcode) {
this.qrcode = qrcode;
}
public boolean getEnable() {
return this.enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public Integer getMinimumStockLevel() {
return this.minimumStockLevel;
}
public void setMinimumStockLevel(Integer minimumStockLevel) {
this.minimumStockLevel = minimumStockLevel;
}
public Integer getStockReorderLevel() {
return this.stockReorderLevel;
}
public void setStockReorderLevel(Integer stockReorderLevel) {
this.stockReorderLevel = stockReorderLevel;
}
}
VehicleModel
public class VehicleModel implements java.io.Serializable {
private Integer idvehicleModel;
private String modelName;
private String code;
private boolean enable;
public VehicleModel() {
}
public VehicleModel(String modelName, boolean enable) {
this.modelName = modelName;
this.enable = enable;
}
public Integer getIdvehicleModel() {
return this.idvehicleModel;
}
public void setIdvehicleModel(Integer idvehicleModel) {
this.idvehicleModel = idvehicleModel;
}
public String getModelName() {
return this.modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public boolean getEnable() {
return this.enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
SparePart
public class SparePart implements java.io.Serializable {
private Integer idsparePart;
private String sparePartName;
private String code;
private boolean enable;
public SparePart() {
}
public SparePart(String sparePartName, boolean enable) {
this.sparePartName = sparePartName;
this.enable = enable;
}
public Integer getIdsparePart() {
return this.idsparePart;
}
public void setIdsparePart(Integer idsparePart) {
this.idsparePart = idsparePart;
}
public String getSparePartName() {
return this.sparePartName;
}
public void setSparePartName(String sparePartName) {
this.sparePartName = sparePartName;
}
public boolean getEnable() {
return this.enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
Here are my XML mappings
Product.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 4, 2020 1:35:36 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.Product" table="product" catalog="aaa" optimistic-lock="version">
<id name="idproduct" type="java.lang.Integer">
<column name="idproduct" />
<generator class="identity" />
</id>
<many-to-one name="sparePart" class="beans.SparePart" fetch="select">
<column name="idspare_part" not-null="true" />
</many-to-one>
<many-to-one name="vehicleModel" class="beans.VehicleModel" fetch="select">
<column name="idvehicle_model" not-null="true" />
</many-to-one>
<property name="unitPrice" type="double">
<column name="unit_price" precision="22" scale="0" not-null="true">
<comment>This is the central price for a product. This can change according to the market values.</comment>
</column>
</property>
<property name="qrcode" type="string">
<column name="qrcode" length="45" not-null="true" />
</property>
<property name="enable" type="boolean">
<column name="enable" not-null="true" />
</property>
<property name="minimumStockLevel" type="java.lang.Integer">
<column name="minimum_stock_level" />
</property>
<property name="stockReorderLevel" type="java.lang.Integer">
<column name="stock_reorder_level" />
</property>
</class>
</hibernate-mapping>
Stock.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 4, 2020 1:35:36 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.Stock" table="stock" catalog="aaa" optimistic-lock="version">
<id name="idstock" type="java.lang.Integer">
<column name="idstock" />
<generator class="identity" />
</id>
<many-to-one name="product" class="beans.Product" fetch="select">
<column name="idproduct" not-null="true" />
</many-to-one>
<property name="quantity" type="int">
<column name="quantity" not-null="true" />
</property>
<property name="dateCreated" type="timestamp">
<column name="date_created" length="0" />
</property>
<property name="lastUpdated" type="timestamp">
<column name="last_updated" length="0" />
</property>
</class>
</hibernate-mapping>
SparePart.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 4, 2020 1:35:36 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.SparePart" table="spare_part" catalog="aaa" optimistic-lock="version">
<id name="idsparePart" type="java.lang.Integer">
<column name="idspare_part" />
<generator class="identity" />
</id>
<property name="sparePartName" type="string">
<column name="spare_part_name" length="100" not-null="true" />
</property>
<property name="code" type="string">
<column name="code" length="100"/>
</property>
<property name="enable" type="boolean">
<column name="enable" not-null="true" />
</property>
</class>
</hibernate-mapping>
VehicleModel.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 4, 2020 1:35:36 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.VehicleModel" table="vehicle_model" catalog="aaa" optimistic-lock="version">
<id name="idvehicleModel" type="java.lang.Integer">
<column name="idvehicle_model" />
<generator class="identity" />
</id>
<property name="modelName" type="string">
<column name="model_name" length="100" not-null="true" />
</property>
<property name="code" type="string">
<column name="code" length="100"/>
</property>
<property name="enable" type="boolean">
<column name="enable" not-null="true" />
</property>
</class>
</hibernate-mapping>
Right now I have the following query.
public List<Stock> getAllStock(Session session) {
Query query = session.createQuery("FROM Stock s");
List<Stock> list = (List<Stock>) query.list();
return list;
}
This gives me,
Stock
Product of each Stock
SparePart of each Product
VehicleModel of each Product
However this is extremely slow due to the famous n+1 issue. To get data from each table, this code generated a SQL query, resulting huge amount of sql queries. The more data you have, the more queries this generates . As a result, this is a super slow process. Currently it takes 40 seconds.
Instead I need to write HQL joins and get data with a single SQL query. How can I do this?
You should use JOIN FETCH to tell JPA/Hibernate that that it should load it.
From the Hibernate docs:
If you forget to JOIN FETCH all EAGER associations, Hibernate is going
to issue a secondary select for each and every one of those which, in
turn, can lead to N+1 query issues.
For this reason, you should prefer LAZY associations.
select s from Stock s join fetch s.product p
join fetch p.sparePart sp
join fetch p.vehicleModel v
Please also read the documentation: https://docs.jboss.org/hibernate/orm/5.5/userguide/html_single/Hibernate_User_Guide.html#best-practices-fetching-associations
You can use criteria implementation of hibernate and using alias you can join
Below is some reference code that may help
Criteria c = session.createCriteria(Stock.class, "stock");
c.createAlias("stock.product", "product");//it is like inner join
c.createAlias("product.spare_part","spare_part");
c.createAlias("product.vehicle_model","vehicle_model");
return c.list();
I have been facing an issue of "Repeated column in mapping for entity". Could you kindly help me where i have done mistake on it. I have mentioned my code below.
USERAUDIT.hbm.xml
<hibernate-mapping>
<class name="com.mkyong.user.UserAudit" table="USER_AUDIT_TBL">
<id name="eventId" column="EVENT_ID" type="java.lang.Integer">
<generator class="sequence">
<param name="sequence">AUDIT_SEQUENCE</param>
</generator>
</id>
<property name="userId" type="java.lang.Integer">
<column name="USER_ID" length="10" not-null="true" unique="true" />
</property>
<set name="userAuditDtls" table="USER_AUTI_DTLS_TBL" inverse="true"
lazy="true" fetch="select">
<key>
<column name="EVENT_ID" not-null="true" />
</key>
<one-to-many class="com.mkyong.user.UserAuditDtls" />
</set>
</class>
</hibernate-mapping>
USERAUDIT.java
enter code herepublic class UserAudit implements java.io.Serializable {
private Integer eventId;
private Integer userId;
//private UserAuditDtls userAuditDtls;
private Set<UserAuditDtls> userAuditDtls =
new HashSet<UserAuditDtls>(0);
public UserAudit(Integer eventId, Integer userId, Set<UserAuditDtls> userAuditDtls) {
super();
this.eventId = eventId;
this.userId = userId;
this.userAuditDtls = userAuditDtls;
}
public UserAudit() {
super();
// TODO Auto-generated constructor stub
}
public Integer getEventId() {
return eventId;
}
public void setEventId(Integer eventId) {
this.eventId = eventId;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Set<UserAuditDtls> getUserAuditDtls() {
return userAuditDtls;
}
public void setUserAuditDtls(Set<UserAuditDtls> userAuditDtls) {
this.userAuditDtls = userAuditDtls;
}
}
USERAUDITDTLS.hbm.xml
<hibernate-mapping>
<class name="com.mkyong.user.UserAuditDtls" table="PII_USER_AUTI_DTLS_TBL">
<id name="eventId" type="java.lang.Integer">
<column name="EVENT_ID" />
<generator class="foreign">
<param name="property">userAudit</param>
</generator>
</id>
<many-to-one name="userAudit" class="com.mkyong.user.UserAudit" fetch="select">
<column name="EVENT_ID" not-null="true" />
</many-to-one>
<property name="fieldName" type="string">
<column name="FIELD_NAME" length="100" not-null="true" />
</property>
</class>
</hibernate-mapping>
UserAuditDtls.java
public class UserAuditDtls implements java.io.Serializable {
private Integer eventId;
private UserAudit userAudit;
private String fieldName;
public UserAuditDtls() {
super();
// TODO Auto-generated constructor stub
}
public UserAuditDtls(Integer eventId, UserAudit userAudit, String fieldName) {
super();
this.eventId = eventId;
this.userAudit = userAudit;
this.fieldName = fieldName;
}
public Integer getEventId() {
return eventId;
}
public void setEventId(Integer eventId) {
this.eventId = eventId;
}
public UserAudit getUserAudit() {
return userAudit;
}
public void setUserAudit(UserAudit userAudit) {
this.userAudit = userAudit;
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
}
Main.Java
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
UserAudit audit = new UserAudit();
audit.setUserId(new Integer(100));
session.save(audit);
UserAuditDtls auditDtls = new UserAuditDtls();
auditDtls.setFieldName("Small");
auditDtls.setUserAudit(audit);
audit.getUserAuditDtls().add(auditDtls);
session.save(auditDtls);
session.getTransaction().commit();
Error:
Caused by: org.hibernate.MappingException: Repeated column in mapping for entity: com.mkyong.user.UserAuditDtls column: EVENT_ID (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:676)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:698)
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:720)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:474)
at org.hibernate.mapping.RootClass.validate(RootClass.java:235)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1335)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1838)
at com.mkyong.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:13)
Tables:
USER_AUDIT_TBL
event_id - pk
userid -integer
USER_AUDIT_DTLS_TBL
event_id- fk
fieldname - varchar
problem is <column name="EVENT_ID" not-null="true" /> in USERAUDITDTLS.hbm.xml
I use hibernate to create a rest api. I create a method to get all items in a table.
public List<Language> getAllLanguages(Session session) {
List<Language> languages=(List<Language>)session.createQuery("from Language").list();
return languages;
}
This is my Language.java
public class Language implements java.io.Serializable {
private Integer idlanguage;
private String language;
private Set<Patient> patients = new HashSet<Patient>(0);
public Language() {
}
public Language(String language) {
this.language = language;
}
public Language(String language, Set<Patient> patients) {
this.language = language;
this.patients = patients;
}
public Integer getIdlanguage() {
return this.idlanguage;
}
public void setIdlanguage(Integer idlanguage) {
this.idlanguage = idlanguage;
}
public String getLanguage() {
return this.language;
}
public void setLanguage(String language) {
this.language = language;
}
public Set<Patient> getPatients() {
return this.patients;
}
public void setPatients(Set<Patient> patients) {
this.patients = patients;
}
}
And this is my Patient.java
// Generated Sep 14, 2016 4:33:23 PM by Hibernate Tools 4.3.1
import beans.DiabetesType;
import beans.Illness;
import beans.Language;
import beans.Reminder;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* Patient generated by hbm2java
*/
public class Patient implements java.io.Serializable {
private Integer idpatient;
private DiabetesType diabetesType;
private Language language;
private String customId;
private String diabetesOther;
private String firstName;
private String lastName;
private String userName;
private String password;
private Date dateCreated;
private Date lastUpdated;
private Set<Illness> illnesses = new HashSet<Illness>(0);
private Set<Reminder> reminders = new HashSet<Reminder>(0);
public Patient() {
}
public Patient(Integer idpatient, String password) {
this.idpatient = idpatient;
this.password = password;
}
public Patient(DiabetesType diabetesType, Language language, String customId, String firstName, String userName, String password, Date lastUpdated) {
this.diabetesType = diabetesType;
this.language = language;
this.customId = customId;
this.firstName = firstName;
this.userName = userName;
this.password = password;
this.lastUpdated = lastUpdated;
}
public Patient(DiabetesType diabetesType, Language language, String customId, String diabetesOther, String firstName, String lastName, String userName, String password, Date dateCreated, Date lastUpdated, Set<Illness> illnesses, Set<Reminder> reminders) {
this.diabetesType = diabetesType;
this.language = language;
this.customId = customId;
this.diabetesOther = diabetesOther;
this.firstName = firstName;
this.lastName = lastName;
this.userName = userName;
this.password = password;
this.dateCreated = dateCreated;
this.lastUpdated = lastUpdated;
this.illnesses = illnesses;
this.reminders = reminders;
}
public Integer getIdpatient() {
return this.idpatient;
}
public void setIdpatient(Integer idpatient) {
this.idpatient = idpatient;
}
public DiabetesType getDiabetesType() {
return this.diabetesType;
}
public void setDiabetesType(DiabetesType diabetesType) {
this.diabetesType = diabetesType;
}
public Language getLanguage() {
return this.language;
}
public void setLanguage(Language language) {
this.language = language;
}
public String getCustomId() {
return this.customId;
}
public void setCustomId(String customId) {
this.customId = customId;
}
public String getDiabetesOther() {
return this.diabetesOther;
}
public void setDiabetesOther(String diabetesOther) {
this.diabetesOther = diabetesOther;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getLastUpdated() {
return this.lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public Set<Illness> getIllnesses() {
return this.illnesses;
}
public void setIllnesses(Set<Illness> illnesses) {
this.illnesses = illnesses;
}
public Set<Reminder> getReminders() {
return this.reminders;
}
public void setReminders(Set<Reminder> reminders) {
this.reminders = reminders;
}
}
Important: The beans and mappings are reverse engineered from MySQL database, via NetBeans. I do not need to get any data related to patient when calling getAllLangauges. My language table has only 2 columns, idlanguage and language. Patient table has a foriegn key of language table
Before using this method in rest api , it worked perfectly without any exception. But when I used this in rest api, it created a complexity in there.
I am not using annotations in here. I used hibernate reverse engineering wizard to map above entities . This is my rest api method.
#Path("/language")
public class LanguageJSONService {
#GET
#Path("/getAllLanguages")
#Produces(MediaType.APPLICATION_JSON)
public List<Language> getAllLanguages(){
LanguageService languageService=new LanguageService();
List<Language> list = languageService.getAllLanguages();
return list;
}
}
This is the way how I call the method,
Client client = ClientBuilder.newClient();
List<Language> list = client.target("http://localhost:8080/simple_rest/rest")
.path("/language/getAllLanguages")
.request(MediaType.APPLICATION_JSON)
.get(new GenericType<List<Language>>() {
});
for (int i = 0; i < list.size(); i++) {
System.out.println("Id - " + list.get(i).getIdlanguage() + " Language - " + list.get(i).getLanguage());
}
When I call the method ,
failed to lazily initialize a collection of role: beans.Language.patients, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->beans.Language["patients"])
is occurred.
Interestingly, if I did not close the session, then I get an output like below which is totally something else, seems like it is trying to display its foreign key tables and their foreign key tables and so on...
[{"idlanguage":1,"language":"English","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":
Have any ideas about this problem ?
Update
my configuration file
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/*****</property>
<property name="hibernate.connection.username">*****</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">3000</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
<property name="hibernate.c3p0.preferredTestQuery">SELECT 1</property>
<property name="hibernate.connection.password">************</property>
<mapping resource="beans/Reminder.hbm.xml"/>
<mapping resource="beans/Food.hbm.xml"/>
<mapping resource="beans/Patient.hbm.xml"/>
<mapping resource="beans/Illness.hbm.xml"/>
<mapping resource="beans/Language.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Language.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 14, 2016 4:33:23 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.Language" table="language" catalog="myglukose" optimistic-lock="version">
<id name="idlanguage" type="java.lang.Integer">
<column name="idlanguage" />
<generator class="identity" />
</id>
<property name="language" type="string">
<column name="language" length="45" not-null="true" />
</property>
<set name="patients" table="patient" inverse="true" lazy="true" fetch="select">
<key>
<column name="language_idlanguage" not-null="true" />
</key>
<one-to-many class="beans.Patient" />
</set>
</class>
</hibernate-mapping>
This is my patient mapping file,
Patient.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 14, 2016 4:33:23 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.Patient" table="patient" catalog="myglukose" optimistic-lock="version">
<id name="idpatient" type="java.lang.Integer">
<column name="idpatient" />
<generator class="identity" />
</id>
<many-to-one name="diabetesType" class="beans.DiabetesType" fetch="select">
<column name="diabetes_type_iddiabetes_type" not-null="true" />
</many-to-one>
<many-to-one name="language" class="beans.Language" fetch="select">
<column name="language_idlanguage" not-null="true" />
</many-to-one>
<property name="customId" type="string">
<column name="custom_id" length="45" not-null="true" />
</property>
<property name="diabetesOther" type="string">
<column name="diabetes_other" length="45" />
</property>
<property name="firstName" type="string">
<column name="first_name" length="100" not-null="true" />
</property>
<property name="lastName" type="string">
<column name="last_name" length="100" />
</property>
<property name="userName" type="string">
<column name="user_name" length="45" not-null="true" />
</property>
<property name="password" type="string">
<column name="password" length="45" not-null="true" />
</property>
<property name="dateCreated" type="timestamp">
<column name="date_created" length="19" />
</property>
<property name="lastUpdated" type="timestamp">
<column name="last_updated" length="19" not-null="true">
<comment>Stores the basic information of the patient</comment>
</column>
</property>
<set name="illnesses" table="illness" inverse="true" lazy="true" fetch="select">
<key>
<column name="patient_idpatient" not-null="true" />
</key>
<one-to-many class="beans.Illness" />
</set>
<set name="reminders" table="reminder" inverse="true" lazy="true" fetch="select">
<key>
<column name="patient_idpatient" not-null="true" />
</key>
<one-to-many class="beans.Reminder" />
</set>
</class>
</hibernate-mapping>
Your json converter tries to serialize the whole entity, which contains the list of all patients speaking each language. From what i understood, the list of patient in the json is not expected. So you have three options (ordered in which i would consider them) :
Remove the mapping to patients in Language entity. Do you need to get acces
s to patients from the language entity ? If not remove this mapping.
Create a Language DTO where you transfer your data before exiting the tx layer. This way whoever calls the service will never get a LazyInitException. No surprise : DTO fields are always set eagerly.
Configure your json converter to not serialize the patient fields. You've not said which json lib you're using. Some of them give you an annotation to ignore some fields (#JsonIgnore for Jackson for example), other requires java configuration.
To apply the first solution, update those files this way :
Language.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 14, 2016 4:33:23 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.Language" table="language" catalog="myglukose" optimistic-lock="version">
<id name="idlanguage" type="java.lang.Integer">
<column name="idlanguage" />
<generator class="identity" />
</id>
<property name="language" type="string">
<column name="language" length="45" not-null="true" />
</property>
</class>
</hibernate-mapping>
Language.java
public class Language implements java.io.Serializable {
private Integer idlanguage;
private String language;
protected Language() {
}
public Language(String language) {
this.language = language;
}
public Integer getIdlanguage() {
return this.idlanguage;
}
protected void setIdlanguage(Integer idlanguage) {
this.idlanguage = idlanguage;
}
public String getLanguage() {
return this.language;
}
public void setLanguage(String language) {
this.language = language;
}
}
I've updated the no-arg constructor and setId method to protected. You can even update them to private : only hibernate should ever use them (and it can use private fields / methods).
When you try to access a lazy field you need to do that before the session of hibernate is closed.
When you exit from the context of the session is not possible for hibernate to access the database if needed, so a LazyInitializationException is thrown.
From javadoc:
Indicates access to unfetched data outside of a session context. For example, when an uninitialized proxy or collection is accessed after the session was closed.
From current explanation I am not able to see you are doing like : language.getPatients();
But if you are writing HQL query to access all patients form Language Entity then I think you should use join . As i can see the exception if related to LazyInitializationException in beans.Language.patients.
so i will suggest below code ...Check if it usefull to you or not..
public List<Language> getAllLanguages(Session session) {
List<Language> languages=(List<Language>)session.createQuery("from Language as l JOIN l.patients").list();
return languages;
}
I had three table i.e,personalinfo,groups_designation,groups_desig_category
personalinfo:pid(personal id)
groups_designation:gid(group id)
groups_desig_category:gid,pid
Actually I have data in both table's (personalinfo,groups_designation).So we have provide one screen.In that,The user selects the group and assign personal id and the data pulled into groups_desig_category table.In this scenario,i mapped like
Personal.hbm.xml:-
<set name="empwthgrp" inverse="true" lazy="true" table="groups_desig_category">
<key>
<column name="pid" not-null="true" />
</key>
<many-to-many entity-name="com.aims.beans.DesignationGroupBean">
<column name="gid" not-null="true" />
</many-to-many>
</set>
Personal.java:-
/**
*
*/
private static final long serialVersionUID = 1L;
private int pid,deptno;
private String name,designation;
private Address address;
private Address permentaddress;
private Set famildtlslst;
private Set empwthgrp=new HashSet();
public Set getEmpwthgrp() {
return empwthgrp;
}
public void setEmpwthgrp(Set empwthgrp) {
this.empwthgrp = empwthgrp;
}
public Set getFamildtlslst() {
return famildtlslst;
}
public void setFamildtlslst(Set famildtlslst) {
this.famildtlslst = famildtlslst;
}
public Address getPermentaddress() {
return permentaddress;
}
public void setPermentaddress(Address permentaddress) {
this.permentaddress = permentaddress;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public int getDeptno() {
return deptno;
}
public void setDeptno(int deptno) {
this.deptno = deptno;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
GroupingDesig.hbm.xml:-
<class name="beans.DesignationGroupBean" table="groups_designation" proxy=beans.DesignationGroupBean">
<id name="gid" column="gid" type="java.lang.Integer">
<generator class="sequence"><param name="sequence">gid_seq</param> </generator>
</id>
<property name="gname" type="java.lang.String" column="gname" not-null="true" />
<property name="description" type="java.lang.String" column="description" not-null="true" />
<set name="grpwthemp" inverse="true" lazy="true" table="groups_desig_category">
<key>
<column name="gid" not-null="true" />
</key>
<many-to-many entity-name="com.aims.beans.Personal">
<column name="pid" not-null="true" />
</many-to-many>
</set>
</class>
DesignationGroupBean.java:-
private int gid;
private String gname,description;
private Set grpwthemp=new HashSet();
public Set getGrpwthemp() {
return grpwthemp;
}
public void setGrpwthemp(Set grpwthemp) {
this.grpwthemp = grpwthemp;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public int getGid() {
return gid;
}
public void setGid(int gid) {
this.gid = gid;
}
public String getGname() {
return gname;
}
public void setGname(String gname) {
this.gname = gname;
}
Actually I trying session.saveOrUpdate(pBean).But its not working.May be can change one-to many and many-to-one instead of many-to-many relation.I think it is not suitable in this scenario.So,How to handle in this scenario?.If you using reverse engineering then it created as one-to-many and many-to-one relation? why?.Please help me.
Update:-
I am implemented in one-to-many and many-to-one relation hibernate whereas in database its many-to-many relation.then Its working fine and below pasted the hibernate mapping files with one-to-many relation ship
GroupingDesig.hbm.xml:-
<set name="grpwthemp" inverse="true" lazy="true" table="groups_desig_category">
<key>
<column name="gid" not-null="true" />
</key>
<one-to-many class="com.aims.beans.GroupAssignment"/>
<!-- <many-to-many entity-name="com.aims.beans.Personal">
<column name="pid" not-null="true" />
</many-to-many>-->
</set>
Personal.hbm.xml
<set name="empwthgrp" inverse="true" lazy="true" table="groups_desig_category">
<key>
<column name="pid" not-null="true" />
</key>
<one-to-many class="com.aims.beans.GroupAssignment"/>
<!--
<many-to-many entity-name="com.aims.beans.DesignationGroupBean">
<column name="gid" not-null="true" />
</many-to-many>-->
</set>
AssigGroupingDesig.hbm.xml:-
<many-to-one name="personal" column="pid" class="com.aims.beans.Personal" not-null="true"></many-to-one>
<many-to-one name="desigdt" column="gid" class="com.aims.beans.DesignationGroupBean" not-null="true"></many-to-one>
When will be came picture the relation ship?.I have search many-to-many relation example's in web i.e,.
Mykong many-to-many
Please help me.My Question is when will be came/used many-to-many relation ship in real time?.
Update 2:-
Thanks.Removing the inverse tag its working fine.But i have doubt regarding generation of deleting the query.Please check the logs
/* load com.beans.Personal */ select personal0_.pid as pid0_, personal0_.name as name5_0_, personal0_.DEPTNO as DEPTNO5_0_, personal0_.designation as designat4_5_0_, personal0_.pddress1 as pddress5_5_0_, personal0_.pddress2 as pddress6_5_0_, personal0_.pcity as pcity5_0_, personal0_.pstate as pstate5_0_, personal0_1_.HomeAddress1 as HomeAddr2_7_0_, personal0_1_.HomeAddress2 as HomeAddr3_7_0_, personal0_1_.homecity as homecity7_0_, personal0_1_.homestate as homestate7_0_ from personalinfo personal0_, address personal0_1_ where personal0_.pid=personal0_1_.pid and personal0_.pid=?
delete collection com.beans.Personal.empwthgrp */ delete from groups_desig_category where pid=?
insert collection row com.beans.Personal.empwthgrp */ insert into groups_desig_category (pid, gid) values (?, ?)
why generating the "delete from groups_desig_category where pid=?".Plz help me
Update 3:-
Yes.Iam loading the data using session.get.becuase i got exception regarding the some of mandatory fields.that is reason i loaded the data then update the records
per=(Personal)session.get(Personal.class,new Integer(pBean.getPid()));
per.setEmpwthgrp(pBean.getEmpwthgrp());
session.saveOrUpdate(per);
In your many-to-many mappings, you set both of them to inverse. You need to choose one entity that will own the relationship - for that one, in the mapping, you will remove the inverse="true" setting. That will be the entity that, when saved or updated, will persist the person to group relationship.
Since in your question you posted saveOrUpdate(pBean), and I assume pBean is Personal entity, then you need to remove the inverse="true" setting in Personal.hbm.xml.
More info in the reference documentation: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/associations.html#assoc-bidirectional-join-m2m
I have a Parent entity that refers a Child entity as a value in a map. The key in the map is an enum (see below for straightforward code). Unfortunately using #AuditJoinTable with a table name doesn't create the expected "parent_children_aud" table.
Is auditing for map references supported? Or is there something that I'm doing wrong?
Using Hibernate 3.6.0.
Parent class:
#Audited
public class Parent {
private Long id;
private Integer version;
private Map<MyEnum, Child> mappedChildren;
protected Parent() {}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
#AuditJoinTable(name = "parent_children_aud")
public Map<MyEnum, Child> getMappedChildren() {
return this.mappedChildren;
}
public void setMappedChildren(Map<MyEnum, TemplateStage> mappedChildren) {
this.mappedChildren = mappedChildren;
}
}
Child class:
#Audited
public class Child {
private Long id;
protected Child() {}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getVersion() {
return version;
}
public void setVersion(Integer version) {
this.version = version;
}
}
MyEnum:
public enum MyEnum { AAA, BBB, CCC; }
hbm.xml:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
-//Hibernate/Hibernate Mapping DTD 3.0//EN
http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd>
<hibernate-mapping>
<class name="Parent" table="parents">
<cache usage="read-write"/>
<id name="id" column="id">
<generator class="native"/>
</id>
<version name="version" unsaved-value="negative"/>
<map name="mappedChildren" cascade="all-delete-orphan" lazy="true">
<cache usage="read-write"/>
<key column="parent_id"/>
<map-key type="MyEnum"/>
<one-to-many class="Child"/>
</map>
</class>
<class name="Child" table="children">
<cache usage="read-write"/>
<id name="id">
<generator class="native"/>
</id>
<version name="version" unsaved-value="negative"/>
</class>
</hibernate-mapping>