Hibernate: Unable to query a database table using a Foreign Key - java

I am trying to fire the following Hibernare quarry.
Query query = session.createSQLQuery("from Rating as rating where rating.organization.idorganization = :idorganization");
I always ended up with the error
hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from Rating as rating where rating.organization.idorganization = 65' at line 1
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Below is my Rating bean
public class Rating implements java.io.Serializable {
private Integer idrating;
private Organization organization;
private User user;
private double rating;
private Date dateCreated;
private Date lastUpdated;
public Rating() {
}
public Rating(Organization organization, User user, double rating) {
this.organization = organization;
this.user = user;
this.rating = rating;
}
public Rating(Organization organization, User user, double rating, Date dateCreated, Date lastUpdated) {
this.organization = organization;
this.user = user;
this.rating = rating;
this.dateCreated = dateCreated;
this.lastUpdated = lastUpdated;
}
public Integer getIdrating() {
return this.idrating;
}
public void setIdrating(Integer idrating) {
this.idrating = idrating;
}
public Organization getOrganization() {
return this.organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public double getRating() {
return this.rating;
}
public void setRating(double rating) {
this.rating = rating;
}
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;
}
}
Below is the Rating.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 19, 2020 8:15:23 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.Rating" table="rating" catalog="autocircle" optimistic-lock="version">
<id name="idrating" type="java.lang.Integer">
<column name="idrating" />
<generator class="identity" />
</id>
<many-to-one name="organization" class="beans.Organization" fetch="select">
<column name="idorganization" not-null="true" />
</many-to-one>
<many-to-one name="user" class="beans.User" fetch="select">
<column name="iduser" not-null="true" />
</many-to-one>
<property name="rating" type="double">
<column name="rating" precision="22" scale="0" 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>
Why am I getting this error?

Since you are using createSQLQuery method, the SQL Statement should be used.
In this case, it should be
"select * from Rating as rating where
rating.organization.idorganization = :idorganization"
Or use the HQL Method and appropriate HQL Query

Related

Bad value for type long in postgres

I am having a java application with Pojo being
public class ArtifactBlobs{
private static final long serialVersionUID = 1L;
private String guid;
private String workspaceId;
private Blob artifactBlobValue;
private Date createdAt;
private Long createdBy;
private Date updatedAt;
private Long updatedBy;
private Set waasArtifactsBlobsMetas = new HashSet(0);
public ArtifactsBlobs() {
}
public ArtifactsBlobs(String guid, Date createdAt, Date updatedAt) {
this.guid = guid;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
public ArtifactsBlobs(String guid, String workspaceId,
Blob artifactBlobValue, Date createdAt, Long createdBy,
Date updatedAt, Long updatedBy) {
this.guid = guid;
this.workspaceId = workspaceId;
this.artifactBlobValue = artifactBlobValue;
this.createdAt = createdAt;
this.createdBy = createdBy;
this.updatedAt = updatedAt;
this.updatedBy = updatedBy;
}
public String getGuid() {
return this.guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public String getWorkspaceId() {
return this.workspaceId;
}
public void setWorkspaceId(String workspaceId) {
this.workspaceId = workspaceId;
}
public Blob getArtifactBlobValue() {
return this.artifactBlobValue;
}
#SuppressWarnings("CPD-START")
public void setArtifactBlobValue(Blob artifactBlobValue) {
this.artifactBlobValue = artifactBlobValue;
}
public Date getCreatedAt() {
return this.createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Long getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
public Date getUpdatedAt() {
return this.updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
public Long getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(Long updatedBy) {
this.updatedBy = updatedBy;
}
public Set getWaasArtifactsBlobsMetas() {
return this.waasArtifactsBlobsMetas;
}
public void setWaasArtifactsBlobsMetas(Set waasArtifactsBlobsMetas) {
this.waasArtifactsBlobsMetas = waasArtifactsBlobsMetas;
}
}
Exactly this method was failing
private ArtifactsBlobs
getArtifactBlobById(
String workspaceId,
String blobId)
{
public static final String GET_ARTIFACT_BLOB_BY_ID = "from ArtifactsBlobs A where A.guid = :blobId and A.workspaceId = :workspaceId";
Map<String, Object> valuesMap = new HashMap<>();
valuesMap.put("workspaceId", workspaceId);
valuesMap.put("blobId", blobId);
ArtifactsBlobs artifactBlob =
iGenericDAO.getEntity(
SqlQuery.GET_ARTIFACT_BLOB_BY_ID,
valuesMap);
if (artifactBlob == null)
{
// Since the blobId is derived from data stored in artifacts table,
// absence of corr. entry in blobs table indicates data is incorrect in DB
throw new DataIntegrityViolationException(
"An unexpected error has occured while processing the request. Please try again later.");
}
return artifactBlob;
}
And the hibernate bean configuration being
<?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 23 Sep, 2014 12:10:11 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.db.entity.autogen.ArtifactsBlobs" table="artifacts_blobs">
<id name="guid" type="string">
<column name="id" length="36" />
<generator class="assigned" />
</id>
<property name="workspaceId" type="string">
<column name="workspace_id" length="36" />
</property>
<property name="artifactBlobValue" type="blob">
<column name="artifact_blob_value" not-null="true"/>
</property>
<property name="createdAt" type="timestamp">
<column name="created_at" length="19" not-null="true" />
</property>
<property name="createdBy" type="java.lang.Long">
<column name="created_by" />
</property>
<property name="updatedAt" type="timestamp">
<column name="updated_at" length="19" not-null="true" />
</property>
<property name="updatedBy" type="java.lang.Long">
<column name="updated_by" />
</property>
<set name="waasArtifactsBlobsMetas" table="waas_artifacts_blobs_meta" inverse="true" lazy="true" fetch="select">
<key>
<column name="blob_id" length="36" not-null="true" />
</key>
<one-to-many class="com.kony.waas.db.entity.autogen.WaasArtifactsBlobsMeta" />
</set>
</class>
</hibernate-mapping>
and the Db Structure is
CREATE TABLE artifacts_blobs (
id varchar(36) NOT NULL,
workspace_id varchar(36) NOT NULL,
artifact_blob_value bytea NOT NULL,
created_at timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
created_by bigint NOT NULL,
updated_at timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_by bigint NOT NULL,
PRIMARY KEY (id)
) ;
The saving of the POJO class is going fine but while retrieving I am facing this error
javax.persistence.PersistenceException: org.hibernate.exception.DataException: could not execute query
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154) ~[hibernate-core-5.3.20.Final.jar:5.3.20.Final]
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1575) ~[hibernate-core-5.3.20.Final.jar:5.3.20.Final]
at org.hibernate.query.internal.AbstractProducedQuery.uniqueResult(AbstractProducedQuery.java:1608) ~[hibernate-core-5.3.20.Final.jar:5.3.20.Final]
Caused by: org.postgresql.util.PSQLException: Bad value for type long : \x35313162373838396435613932383937613638303266336663303236633964366332393838393638356663613039323163623538383562666164366163643039306633656335613162333734313638353539303335343662306336666164343232353362306261306
at org.postgresql.jdbc.PgResultSet.toLong(PgResultSet.java:3253) ~[postgresql-42.5.0.jar:42.5.0]
at org.postgresql.jdbc.PgResultSet.getLong(PgResultSet.java:2436) ~[postgresql-42.5.0.jar:42.5.0]
at org.postgresql.jdbc.PgResultSet.getBlob(PgResultSet.java:456) ~[postgresql-42.5.0.jar:42.5.0]
at org.postgresql.jdbc.PgResultSet.getBlob(PgResultSet.java:442) ~[postgresql-42.5.0.jar:42.5.0]

Hibernate: How to write Join queries including multi levels?

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();

Hibernate: could not initialize proxy - no Session (through reference chain....)

Note: Before anyone complain about this is a duplicate, make sure to go through the content without judging by title. Also make sure to read your reference question and the answer carefully to see whether it is duplicate. As of my experience now, the issue in this question can happen under different environments. For an example, the answer for someone using the below code in jsp will be different, for someone using Spring will be different and for someone whose DB is small and eager load is fine will be different. And no, my situation is not any of them.
I am writing a REST api using Hibernateand Jersey. Please have a look at the below code.
VerificationCodeJSONService.java - The JSON Service class
#Path("/verificaion_code")
public class VerificationCodeJSONService {
#GET
#Path("/getAllVerificationCodes")
#Produces(MediaType.APPLICATION_JSON)
public List<VerificaionCode> getAllVerificationCodes() {
VerificationCodeService verificationCodeService=new VerificationCodeService();
List<VerificaionCode> list = verificationCodeService.getAllVerificationCodes();
return list;
}
}
VerificationCodeService.java - The Service Layer
public class VerificationCodeService {
private static VerificationCodeDAOInterface verificationCodeDAOInterface;
public VerificationCodeService() {
verificationCodeDAOInterface = new VerificationCodeDAOImpl();
}
public List<VerificaionCode> getAllVerificationCodes() {
Session session = verificationCodeDAOInterface.openCurrentSession();
Transaction transaction = null;
List<VerificaionCode> verificaionCodes = new ArrayList<VerificaionCode>();
try {
transaction = verificationCodeDAOInterface.openTransaction(session);
verificaionCodes = verificationCodeDAOInterface.getAllVerificationCodes(session);
transaction.commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
session.close();
}
return verificaionCodes;
}
}
VerificationCodeDAOImpl.java - The database layer
public class VerificationCodeDAOImpl implements VerificationCodeDAOInterface{
private static final SessionFactoryBuilder sessionFactoryBuilder = SessionFactoryBuilder.getInstance();
#Override
public List<VerificaionCode> getAllVerificationCodes(Session session) {
List<VerificaionCode> verificaionCodes=(List<VerificaionCode>)session.createQuery("from VerificaionCode").list();
return verificaionCodes;
}
}
VerificationCode.java - The DAO layer
public class VerificaionCode implements java.io.Serializable {
private Integer idverificaionCode;
private Patient patient;
private String code;
private Date dateCreated;
private Date lastUpdated;
public VerificaionCode() {
}
public VerificaionCode(Patient patient, String code, Date lastUpdated) {
this.patient = patient;
this.code = code;
this.lastUpdated = lastUpdated;
}
public VerificaionCode(Patient patient, String code, Date dateCreated, Date lastUpdated) {
this.patient = patient;
this.code = code;
this.dateCreated = dateCreated;
this.lastUpdated = lastUpdated;
}
public Integer getIdverificaionCode() {
return this.idverificaionCode;
}
public void setIdverificaionCode(Integer idverificaionCode) {
this.idverificaionCode = idverificaionCode;
}
public Patient getPatient() {
return this.patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
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;
}
}
Patient.java - The DAO layer
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 email;
private Date dob;
private String parentEmail;
private String gender;
private Date diagnosedDate;
private Double height;
private Double weight;
private String heightUnit;
private String weightUnit;
private String theme;
private String userName;
private String password;
private Date dateCreated;
private Date lastUpdated;
public Patient() {
}
public Patient(DiabetesType diabetesType, Language language, String customId, String firstName, String email, Date dob, String gender, String theme, String userName, String password, Date lastUpdated) {
this.diabetesType = diabetesType;
this.language = language;
this.customId = customId;
this.firstName = firstName;
this.email = email;
this.dob = dob;
this.gender = gender;
this.theme = theme;
this.userName = userName;
this.password = password;
this.lastUpdated = lastUpdated;
}
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 getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDob() {
return this.dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getParentEmail() {
return this.parentEmail;
}
public void setParentEmail(String parentEmail) {
this.parentEmail = parentEmail;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getDiagnosedDate() {
return this.diagnosedDate;
}
public void setDiagnosedDate(Date diagnosedDate) {
this.diagnosedDate = diagnosedDate;
}
public Double getHeight() {
return this.height;
}
public void setHeight(Double height) {
this.height = height;
}
public Double getWeight() {
return this.weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
public String getHeightUnit() {
return this.heightUnit;
}
public void setHeightUnit(String heightUnit) {
this.heightUnit = heightUnit;
}
public String getWeightUnit() {
return this.weightUnit;
}
public void setWeightUnit(String weightUnit) {
this.weightUnit = weightUnit;
}
public String getTheme() {
return this.theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
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;
}
}
Below are my Hibernate mapping files for the above POJOs
VerificaionCode.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 23, 2016 3:21:00 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.VerificaionCode" table="verificaion_code" catalog="myglukose" optimistic-lock="version">
<id name="idverificaionCode" type="java.lang.Integer">
<column name="idverificaion_code" />
<generator class="identity" />
</id>
<many-to-one name="patient" class="beans.Patient" fetch="select">
<column name="patient_idpatient" not-null="true" />
</many-to-one>
<property name="code" type="string">
<column name="code" 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" />
</property>
</class>
</hibernate-mapping>
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 23, 2016 3:21:00 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="email" type="string">
<column name="email" length="45" not-null="true" />
</property>
<property name="dob" type="date">
<column name="dob" length="10" not-null="true" />
</property>
<property name="parentEmail" type="string">
<column name="parent_email" length="45" />
</property>
<property name="gender" type="string">
<column name="gender" length="45" not-null="true" />
</property>
<property name="diagnosedDate" type="date">
<column name="diagnosed_date" length="10" />
</property>
<property name="height" type="java.lang.Double">
<column name="height" precision="22" scale="0" />
</property>
<property name="weight" type="java.lang.Double">
<column name="weight" precision="22" scale="0" />
</property>
<property name="heightUnit" type="string">
<column name="height_unit" length="45" />
</property>
<property name="weightUnit" type="string">
<column name="weight_unit" length="45" />
</property>
<property name="theme" type="string">
<column name="theme" length="45" not-null="true" />
</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>
</class>
</hibernate-mapping>
However when I run this code via http://localhost:8080/example_rest/rest/verificaion_code/getAllVerificationCodes I am getting the below error.
could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->beans.VerificaionCode["patient"]->beans.Patient_$$_jvst40f_7["diabetesType"])
As you can see diabetesType is an Object (Foreign Key) in the patient's table and has nothing to do with VerificationCode. How can I fix this up?
Please note that this is a REST API. So I can't load these in a JSP like in a web app.
Update
As #Kayaman recommended, I made the updates by making null. Please check the below code. I noticed that verificaionCodes.get(i).getPatient().set...(null) makes the same error as above, so I tried below which started working fine.
VerificationCodeService.java
public List<VerificaionCode> getAllVerificationCodes() {
Session session = verificationCodeDAOInterface.openCurrentSession();
Transaction transaction = null;
List<VerificaionCode> verificaionCodes = new ArrayList<VerificaionCode>();
try {
transaction = verificationCodeDAOInterface.openTransaction(session);
verificaionCodes = verificationCodeDAOInterface.getAllVerificationCodes(session);
transaction.commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
session.close();
for(int i=0;i<verificaionCodes.size();i++)
{
Patient p = new Patient();
System.out.println(verificaionCodes.get(i).getPatient().getIdpatient());
Integer idpatient = verificaionCodes.get(i).getPatient().getIdpatient();
p.setIdpatient(idpatient);
verificaionCodes.get(i).setPatient(p);
}
}
return verificaionCodes;
}

Hibernate- failed to lazily initialize a collection of role: beans.Language.patients, could not initialize proxy - no Session

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

How to insert data to multiple table at once in hibernate using java

Hi I am using hibernate to save data into two tables on a database .Also, I am using mysql .
These are my POJO classes,
Patient.java
public class Patient implements java.io.Serializable {
private Integer idPatient;
private String title;
private String firstName;
private String lastName;
private String middleName;
private Date dob;
private Boolean martitalStatus;
private String gender;
private String nic;
private Date dateCreated;
private Date lastUpdated;
private Set<Contact> contacts = new HashSet<Contact>(0);
public Patient() {
}
public Patient(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public Patient(String title, String firstName, String lastName, String middleName, Date dob, Boolean martitalStatus, String gender, String nic, Date dateCreated, Date lastUpdated, Set<Contact> contacts) {
this.title = title;
this.firstName = firstName;
this.lastName = lastName;
this.middleName = middleName;
this.dob = dob;
this.martitalStatus = martitalStatus;
this.gender = gender;
this.nic = nic;
this.dateCreated = dateCreated;
this.lastUpdated = lastUpdated;
this.contacts = contacts;
}
public Integer getIdPatient() {
return this.idPatient;
}
public void setIdPatient(Integer idPatient) {
this.idPatient = idPatient;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
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 getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public Date getDob() {
return this.dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Boolean getMartitalStatus() {
return this.martitalStatus;
}
public void setMartitalStatus(Boolean martitalStatus) {
this.martitalStatus = martitalStatus;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNic() {
return this.nic;
}
public void setNic(String nic) {
this.nic = nic;
}
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<Contact> getContacts() {
return this.contacts;
}
public void setContacts(Set<Contact> contacts) {
this.contacts = contacts;
}
}
Contact.java
public class Contact implements java.io.Serializable {
private Integer idContact;
private Patient patient;
private String telephone;
private String address;
public Contact() {
}
public Contact(Patient patient) {
this.patient = patient;
}
public Contact(Patient patient, String telephone, String address) {
this.patient = patient;
this.telephone = telephone;
this.address = address;
}
public Integer getIdContact() {
return this.idContact;
}
public void setIdContact(Integer idContact) {
this.idContact = idContact;
}
public Patient getPatient() {
return this.patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public String getTelephone() {
return this.telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
}
Also I am not using annotations in here.
Patient patient=new Patient();
Contact contact=new Contact();
Set<Contact> contacts=new HashSet<Contact>();
contact.setTelephone("0358965458");
contact.setAddress("Horana");
contacts.add(contact);
patient.setFirstName("Wajira");
patient.setLastName("Dahanushka");
patient.setDateCreated(Common.getSQLCurrentTimeStamp());
patient.setLastUpdated(Common.getSQLCurrentTimeStamp());
patient.setGender("Male");
patient.setTitle("Mr");
patient.setNic("9115580466v");
patient.setContacts(contacts);
SessionFactory sessionFactory=new HibernateUtil().getSessionFactory();
Session session=sessionFactory.openSession();
session.beginTransaction();
session.persist(patient);
session.getTransaction().commit();
HibernateUtil.shutdown();
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 8, 2016 9:56:01 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="db.Patient" table="patient" catalog="example_hibernate" optimistic-lock="version">
<id name="idPatient" type="java.lang.Integer">
<column name="idPatient" />
<generator class="identity" />
</id>
<property name="title" type="string">
<column name="title" length="45" />
</property>
<property name="firstName" type="string">
<column name="firstName" length="45" />
</property>
<property name="lastName" type="string">
<column name="lastName" length="45" />
</property>
<property name="middleName" type="string">
<column name="middleName" length="45" />
</property>
<property name="dob" type="date">
<column name="dob" length="10" />
</property>
<property name="martitalStatus" type="java.lang.Boolean">
<column name="martitalStatus" />
</property>
<property name="gender" type="string">
<column name="gender" length="45" />
</property>
<property name="nic" type="string">
<column name="nic" length="45" />
</property>
<property name="dateCreated" type="timestamp">
<column name="dateCreated" length="19" />
</property>
<property name="lastUpdated" type="timestamp">
<column name="lastUpdated" length="19" not-null="true" />
</property>
<set name="contacts" table="contact" inverse="true" lazy="true" fetch="select">
<key>
<column name="idPatient" not-null="true" />
</key>
<one-to-many class="db.Contact" />
</set>
</class>
</hibernate-mapping>
Contact.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 8, 2016 9:56:01 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="db.Contact" table="contact" catalog="example_hibernate" optimistic-lock="version">
<id name="idContact" type="java.lang.Integer">
<column name="idContact" />
<generator class="identity" />
</id>
<many-to-one name="patient" class="db.Patient" fetch="select">
<column name="idPatient" not-null="true" />
</many-to-one>
<property name="telephone" type="string">
<column name="telephone" length="45" />
</property>
<property name="address" type="string">
<column name="address" length="45" />
</property>
</class>
</hibernate-mapping>
Contact table has a foreign key which is the primary key of the patient table.
When I run above code , A new patient record could see in patient table but couldn't see any new contact record in contact table .
Is there anything wrong.
Have any ideas .
You need to tell Hibernate that you have a one to many relationship betweens patients and their contacts. After you have done this, persisting a Patient object should also persist the entire graph of that patient. If you were using annotations, then something like this should work:
#Entity
#Table(name="Patient")
public class Patient {
#OneToMany(mappedBy="patient")
private Set<Contact> contacts;
}
#Entity
#Table(name="Contact")
public class Contact {
#ManyToOne
private Patient patient;
}
in Patient.hbm.xml
while mentioning the set for contacts, use the following cascade property
<set name="contacts" table="contact" cascade="save-update" inverse="true" lazy="true" fetch="select">
<key>
<column name="idPatient" not-null="true" />
</key>
<one-to-many class="db.Contact" />
</set>
By mentioning cascade as save-update, you just have to invoke session.save(patientObj), and contact details will automatically get persisted.
Check this link for complete reference of cascading updates/inserts/delete operation in hibernate associations.

Categories

Resources