Repeated column in mapping for entity in hibernate XML mapping - java

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

Related

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

org.hibernate.MappingException: Foreign key () must have same number of columns as the referenced primary key ()

I know this topic is discussed a lot of times here, but I am still stuck on an exception: Foreign key must have same number of columns as the referenced primary key.
I am using Hibernate for mapping via xml file:
public class Product implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private Integer idProduct;
private String titleProduct;
private String reference;
private String description;
private boolean deuxiemeMain;
private double prixUnitaire;
private double prixNegocier;
private boolean valider;
private Integer qteMinOrdred;
private String echantillonGratuit;
private Customer costumer;
private SubCategory subCategory;
private Order order;
private ProductType productType;
private Unity unity;
private byte[] image;
private Collection<Double> prices;
private Collection<Integer> quantities;
private Collection<String> keyWords;
public Product() {
// TODO Auto-generated constructor stub
}
public Integer getIdProduct() {
return idProduct;
}
public String getTitleProduct() {
return titleProduct;
}
public String getReference() {
return reference;
}
public String getDescription() {
return description;
}
public boolean isDeuxiemeMain() {
return deuxiemeMain;
}
public double getPrixUnitaire() {
return prixUnitaire;
}
public double getPrixNegocier() {
return prixNegocier;
}
public boolean isValider() {
return valider;
}
public Integer getQteMinOrdred() {
return qteMinOrdred;
}
public String getEchantillonGratuit() {
return echantillonGratuit;
}
public void setIdProduct(Integer idProduct) {
this.idProduct = idProduct;
}
public void setTitleProduct(String titleProduct) {
this.titleProduct = titleProduct;
}
public void setReference(String reference) {
this.reference = reference;
}
public void setDescription(String description) {
this.description = description;
}
public void setDeuxiemeMain(boolean deuxiemeMain) {
this.deuxiemeMain = deuxiemeMain;
}
public void setPrixUnitaire(double prixUnitaire) {
this.prixUnitaire = prixUnitaire;
}
public void setPrixNegocier(double prixNegocier) {
this.prixNegocier = prixNegocier;
}
public void setValider(boolean valider) {
this.valider = valider;
}
public void setQteMinOrdred(Integer qteMinOrdred) {
this.qteMinOrdred = qteMinOrdred;
}
public void setEchantillonGratuit(String echantillonGratuit) {
this.echantillonGratuit = echantillonGratuit;
}
public Customer getCostumer() {
return costumer;
}
public void setCostumer(Customer costumer) {
this.costumer = costumer;
}
public ProductType getProductType() {
return productType;
}
public void setProductType(ProductType productType) {
this.productType = productType;
}
public Collection<String> getKeyWords() {
return keyWords;
}
public void setKeyWords(Collection<String> keyWords) {
this.keyWords = keyWords;
}
public Unity getUnity() {
return unity;
}
public void setUnity(Unity unity) {
this.unity = unity;
}
public SubCategory getSubCategory() {
return subCategory;
}
public void setSubCategory(SubCategory subCategory) {
this.subCategory = subCategory;
}
public Order getOrder() {
return order;
}
public void setOrder(Order order) {
this.order = order;
}
public byte[] getImage() {
return image;
}
public void setImage(byte[] image) {
this.image = image;
}
public Collection<Double> getPrices() {
return prices;
}
public Collection<Integer> getQuantities() {
return quantities;
}
public void setPrices(Collection<Double> prices) {
this.prices = prices;
}
public void setQuantities(Collection<Integer> quantities) {
this.quantities = quantities;
}
}
My Mapping file for Product Class is:
<hibernate-mapping>
<class name="modele.Product" table="PRODUCT">
<id name="idProduct" type="java.lang.Integer">
<column name="IDPRODUCT" />
<generator class="increment" />
</id>
<property name="titleProduct" type="java.lang.String">
<column name="TITLEPRODUCT" />
</property>
<property name="reference" type="java.lang.String">
<column name="REFERENCE" />
</property>
<property name="description" type="java.lang.String">
<column name="DESCRIPTION" />
</property>
<property name="deuxiemeMain" type="boolean">
<column name="DEUXIEMEMAIN" />
</property>
<property name="prixUnitaire" type="double">
<column name="PRIXUNITAIRE" />
</property>
<property name="prixNegocier" type="double">
<column name="PRIXNEGOCIER" />
</property>
<property name="valider" type="boolean">
<column name="VALIDER" />
</property>
<property name="qteMinOrdred" type="java.lang.Integer">
<column name="QTEMINORDRED" />
</property>
<property name="echantillonGratuit" type="java.lang.String">
<column name="ECHANTILLONGRATUIT" />
</property>
<many-to-one name="costumer" class="modele.Customer"
fetch="join">
<column name="COSTUMER" />
</many-to-one>
<many-to-one name="subCategory" class="modele.SubCategory"
fetch="join">
<column name="SUBCATEGORY" />
</many-to-one>
<many-to-one name="order" class="modele.Order" fetch="join">
<column name="ORDER" />
</many-to-one>
<many-to-one name="productType" class="modele.ProductType"
fetch="join">
<column name="PRODUCTTYPE" />
</many-to-one>
<many-to-one name="unity" class="modele.Unity" fetch="join">
<column name="UNITY" />
</many-to-one>
<primitive-array name="image" table="PRODUCT">
<key>
<column name="IDPRODUCT" />
</key>
<index></index>
<element type="byte">
<column name="IMAGE" />
</element>
</primitive-array>
<bag name="prices" table="PRODUCT" inverse="false" lazy="true">
<key>
<column name="IDPRODUCT" />
</key>
<element type="java.lang.Double">
<column name="PRICES" />
</element>
</bag>
<bag name="quantities" table="PRODUCT" inverse="false" lazy="true">
<key>
<column name="IDPRODUCT" />
</key>
<element type="java.lang.Integer">
<column name="QUANTITIES" />
</element>
</bag>
<bag name="keyWords" table="PRODUCT" inverse="false" lazy="true">
<key>
<column name="IDPRODUCT" />
</key>
<element type="java.lang.String">
<column name="KEYWORDS" />
</element>
</bag>
</class>
</hibernate-mapping>
I get for this construction the following exception:
org.hibernate.MappingException: Foreign key (FK185958CF30AA9EB1:PRODUCT [IDPRODUCT])) must have same number of columns as the referenced primary key (PRODUCT [IDPRODUCT,idx])
org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:90)
org.hibernate.mapping.ForeignKey.alignColumns(ForeignKey.java:73)
org.hibernate.cfg.Configuration.secondPassCompileForeignKeys(Configuration.java:1263)
org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1170)
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1286)
persistence.BaseDAO.(BaseDAO.java:21)
persistence.BaseDAO.getInstance(BaseDAO.java:42)
dao.SearchDAO.getListeProducts(SearchDAO.java:23)
metier.SearchManager.getProduct(SearchManager.java:13)
presentation.SearchProduct.doGet(SearchProduct.java:40)
javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

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

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.

Object is Returned null in Hibernate Select query

i Have this following query that i am using in hibernate
select a.*, b.cur_date, c.value as maxloginattempts
from tbl_user a, tbl_eod_bod_stat b, tbl_settings c
where upper(a.id) = 'ADMIN'
and usr_status in ('A','E','O','P','U','G','M','D','T') and c.attribute = 'MAX_LOGIN_ATTEMPTS'";
my main class:-
package foo;
import java.sql.Date;
import java.util.Arrays;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.ScrollMode;
import org.hibernate.ScrollableResults;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import com.imageinfo.eclear.hbm.pojo.TblUser;
public class myclass {
static SessionFactory factory;
public static void main(String[] args) {
myclass obj=new myclass();
System.out.println("above buildfactory");
try{
factory=new Configuration().configure().buildSessionFactory();
}catch(Exception e)
{
e.printStackTrace();
}
System.out.println("after buidl");
//obj.raiseEmailNotification();
//obj.doAfter();
//obj.validateInput();
obj.checkPass();
}
public void checkPass(){
String username="S5626";
Session session =factory.openSession();
Transaction tx=session.beginTransaction();
Query query=session.createQuery("select a.id,b.id,c.value as maxloginattempts from TblUser a,TblEodBodStat b,TblSettings c where upper(a.id.id)='ADMIN' and c.attribute='MAX_LOGIN_ATTEMPTS'");
//query.setParameter("username", username);
//List list=query.list();
System.out.println("worked");
int i=0;
List list=query.list();
if(!list.isEmpty())
{
for(Object a:list)
{
Object[] o=(Object[])a;
System.out.println(o[0]);
System.out.println(Arrays.toString(o));
}
}
when i run this the tblUser object is returned null.
OUTPUT
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
after buidl
worked
null
[null, com.imageinfo.eclear.hbm.pojo.TblEodBodStatId#257db8ef, 3]
tblUser.hbm.xml:-
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Dec 3, 2015 4:43:35 PM by Hibernate Tools 3.2.4.GA -->
<hibernate-mapping>
<class name="com.imageinfo.eclear.hbm.pojo.TblUser" table="TBL_USER">
<composite-id name="id" class="com.imageinfo.eclear.hbm.pojo.TblUserId">
<key-property name="id" type="string">
<column name="ID" length="22" />
</key-property>
<key-property name="roleId" type="string">
<column name="ROLE_ID" length="3" />
</key-property>
<key-property name="fname" type="string">
<column name="FNAME" length="60" />
</key-property>
<key-property name="emailId" type="string">
<column name="EMAIL_ID" length="100" />
</key-property>
<key-property name="branchCode" type="string">
<column name="BRANCH_CODE" length="5" />
</key-property>
<key-property name="employeeCode" type="string">
<column name="EMPLOYEE_CODE" length="20" />
</key-property>
<key-property name="departmentCode" type="string">
<column name="DEPARTMENT_CODE" length="10" />
</key-property>
<key-property name="userCategory" type="string">
<column name="USER_CATEGORY" length="1" />
</key-property>
<key-property name="description" type="string">
<column name="DESCRIPTION" length="100" />
</key-property>
<key-property name="loggedStatus" type="java.lang.Byte">
<column name="LOGGED_STATUS" precision="2" scale="0" />
</key-property>
<key-property name="lastLogged" type="timestamp">
<column name="LAST_LOGGED" />
</key-property>
<key-property name="currentSessionId" type="string">
<column name="CURRENT_SESSION_ID" length="34" />
</key-property>
<key-property name="currentAttempts" type="java.lang.Boolean">
<column name="CURRENT_ATTEMPTS" precision="1" scale="0" />
</key-property>
<key-property name="expiryDate" type="date">
<column name="EXPIRY_DATE" length="7" />
</key-property>
<key-property name="expireStatus" type="string">
<column name="EXPIRE_STATUS" length="3" />
</key-property>
<key-property name="allowedForms" type="string">
<column name="ALLOWED_FORMS" length="1000" />
</key-property>
<key-property name="groupId" type="string">
<column name="GROUP_ID" length="50" />
</key-property>
<key-property name="usrActiveStatus" type="string">
<column name="USR_ACTIVE_STATUS" length="1" />
</key-property>
<key-property name="usrStatus" type="string">
<column name="USR_STATUS" length="1" />
</key-property>
<key-property name="idmsStatus" type="string">
<column name="IDMS_STATUS" length="1" />
</key-property>
<key-property name="creator" type="string">
<column name="CREATOR" length="22" />
</key-property>
<key-property name="approver" type="string">
<column name="APPROVER" length="22" />
</key-property>
<key-property name="CSessionid" type="string">
<column name="C_SESSIONID" length="34" />
</key-property>
<key-property name="ASessionid" type="string">
<column name="A_SESSIONID" length="34" />
</key-property>
<key-property name="creatorDate" type="timestamp">
<column name="CREATOR_DATE" />
</key-property>
<key-property name="creatorIpAddress" type="string">
<column name="CREATOR_IP_ADDRESS" length="15" />
</key-property>
<key-property name="approverDate" type="timestamp">
<column name="APPROVER_DATE" />
</key-property>
<key-property name="approverIpAddress" type="string">
<column name="APPROVER_IP_ADDRESS" length="15" />
</key-property>
<key-property name="logoutDate" type="timestamp">
<column name="LOGOUT_DATE" />
</key-property>
<key-property name="lockedStatus" type="string">
<column name="LOCKED_STATUS" length="1" />
</key-property>
<key-property name="userIdentity" type="string">
<column name="USER_IDENTITY" length="20" />
</key-property>
<key-property name="passwd" type="string">
<column name="PASSWD" length="50" />
</key-property>
<key-property name="passHist1" type="string">
<column name="PASS_HIST1" length="50" />
</key-property>
<key-property name="passHist2" type="string">
<column name="PASS_HIST2" length="50" />
</key-property>
<key-property name="passHist3" type="string">
<column name="PASS_HIST3" length="50" />
</key-property>
<key-property name="passHist4" type="string">
<column name="PASS_HIST4" length="50" />
</key-property>
</composite-id>
</class>
</hibernate-mapping>
TblUserId.java
package com.imageinfo.eclear.hbm.pojo;
// Generated Dec 3, 2015 4:43:34 PM by Hibernate Tools 3.2.4.GA
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
/**
* TblUserId generated by hbm2java
*/
public class TblUserId implements java.io.Serializable {
private String id;
private String roleId;
private String fname;
private String emailId;
private String branchCode;
private String employeeCode;
private String departmentCode;
private String userCategory;
private String description;
private Byte loggedStatus;
private Timestamp lastLogged;
private String currentSessionId;
private Boolean currentAttempts;
private Date expiryDate;
private String expireStatus;
private String allowedForms;
private String groupId;
private String usrActiveStatus;
private String usrStatus;
private String idmsStatus;
private String creator;
private String approver;
private String CSessionid;
private String ASessionid;
private Timestamp creatorDate;
private String creatorIpAddress;
private Timestamp approverDate;
private String approverIpAddress;
private Timestamp logoutDate;
private String lockedStatus;
private String userIdentity;
private String passwd;
private String passHist1;
private String passHist2;
private String passHist3;
private String passHist4;
public TblUserId() {
}
public TblUserId(String id, String roleId, String fname, String emailId,
String branchCode, String employeeCode, String departmentCode,
String userCategory, String description, Byte loggedStatus,
Timestamp lastLogged, String currentSessionId,
Boolean currentAttempts, Date expiryDate, String expireStatus,
String allowedForms, String groupId, String usrActiveStatus,
String usrStatus, String idmsStatus, String creator,
String approver, String CSessionid, String ASessionid,
Timestamp creatorDate, String creatorIpAddress,
Timestamp approverDate, String approverIpAddress,
Timestamp logoutDate, String lockedStatus, String userIdentity,
String passwd, String passHist1, String passHist2,
String passHist3, String passHist4) {
this.id = id;
this.roleId = roleId;
this.fname = fname;
this.emailId = emailId;
this.branchCode = branchCode;
this.employeeCode = employeeCode;
this.departmentCode = departmentCode;
this.userCategory = userCategory;
this.description = description;
this.loggedStatus = loggedStatus;
this.lastLogged = lastLogged;
this.currentSessionId = currentSessionId;
this.currentAttempts = currentAttempts;
this.expiryDate = expiryDate;
this.expireStatus = expireStatus;
this.allowedForms = allowedForms;
this.groupId = groupId;
this.usrActiveStatus = usrActiveStatus;
this.usrStatus = usrStatus;
this.idmsStatus = idmsStatus;
this.creator = creator;
this.approver = approver;
this.CSessionid = CSessionid;
this.ASessionid = ASessionid;
this.creatorDate = creatorDate;
this.creatorIpAddress = creatorIpAddress;
this.approverDate = approverDate;
this.approverIpAddress = approverIpAddress;
this.logoutDate = logoutDate;
this.lockedStatus = lockedStatus;
this.userIdentity = userIdentity;
this.passwd = passwd;
this.passHist1 = passHist1;
this.passHist2 = passHist2;
this.passHist3 = passHist3;
this.passHist4 = passHist4;
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public String getRoleId() {
return this.roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getFname() {
return this.fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getEmailId() {
return this.emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getBranchCode() {
return this.branchCode;
}
public void setBranchCode(String branchCode) {
this.branchCode = branchCode;
}
public String getEmployeeCode() {
return this.employeeCode;
}
public void setEmployeeCode(String employeeCode) {
this.employeeCode = employeeCode;
}
public String getDepartmentCode() {
return this.departmentCode;
}
public void setDepartmentCode(String departmentCode) {
this.departmentCode = departmentCode;
}
public String getUserCategory() {
return this.userCategory;
}
public void setUserCategory(String userCategory) {
this.userCategory = userCategory;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Byte getLoggedStatus() {
return this.loggedStatus;
}
public void setLoggedStatus(Byte loggedStatus) {
this.loggedStatus = loggedStatus;
}
public Timestamp getLastLogged() {
return this.lastLogged;
}
public void setLastLogged(Timestamp lastLogged) {
this.lastLogged = lastLogged;
}
public String getCurrentSessionId() {
return this.currentSessionId;
}
public void setCurrentSessionId(String currentSessionId) {
this.currentSessionId = currentSessionId;
}
public Boolean getCurrentAttempts() {
return this.currentAttempts;
}
public void setCurrentAttempts(Boolean currentAttempts) {
this.currentAttempts = currentAttempts;
}
public Date getExpiryDate() {
return this.expiryDate;
}
public void setExpiryDate(Date expiryDate) {
this.expiryDate = expiryDate;
}
public String getExpireStatus() {
return this.expireStatus;
}
public void setExpireStatus(String expireStatus) {
this.expireStatus = expireStatus;
}
public String getAllowedForms() {
return this.allowedForms;
}
public void setAllowedForms(String allowedForms) {
this.allowedForms = allowedForms;
}
public String getGroupId() {
return this.groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getUsrActiveStatus() {
return this.usrActiveStatus;
}
public void setUsrActiveStatus(String usrActiveStatus) {
this.usrActiveStatus = usrActiveStatus;
}
public String getUsrStatus() {
return this.usrStatus;
}
public void setUsrStatus(String usrStatus) {
this.usrStatus = usrStatus;
}
public String getIdmsStatus() {
return this.idmsStatus;
}
public void setIdmsStatus(String idmsStatus) {
this.idmsStatus = idmsStatus;
}
public String getCreator() {
return this.creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getApprover() {
return this.approver;
}
public void setApprover(String approver) {
this.approver = approver;
}
public String getCSessionid() {
return this.CSessionid;
}
public void setCSessionid(String CSessionid) {
this.CSessionid = CSessionid;
}
public String getASessionid() {
return this.ASessionid;
}
public void setASessionid(String ASessionid) {
this.ASessionid = ASessionid;
}
public Timestamp getCreatorDate() {
return this.creatorDate;
}
public void setCreatorDate(Timestamp creatorDate) {
this.creatorDate = creatorDate;
}
public String getCreatorIpAddress() {
return this.creatorIpAddress;
}
public void setCreatorIpAddress(String creatorIpAddress) {
this.creatorIpAddress = creatorIpAddress;
}
public Timestamp getApproverDate() {
return this.approverDate;
}
public void setApproverDate(Timestamp approverDate) {
this.approverDate = approverDate;
}
public String getApproverIpAddress() {
return this.approverIpAddress;
}
public void setApproverIpAddress(String approverIpAddress) {
this.approverIpAddress = approverIpAddress;
}
public Timestamp getLogoutDate() {
return this.logoutDate;
}
public void setLogoutDate(Timestamp logoutDate) {
this.logoutDate = logoutDate;
}
public String getLockedStatus() {
return this.lockedStatus;
}
public void setLockedStatus(String lockedStatus) {
this.lockedStatus = lockedStatus;
}
public String getUserIdentity() {
return this.userIdentity;
}
public void setUserIdentity(String userIdentity) {
this.userIdentity = userIdentity;
}
public String getPasswd() {
return this.passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getPassHist1() {
return this.passHist1;
}
public void setPassHist1(String passHist1) {
this.passHist1 = passHist1;
}
public String getPassHist2() {
return this.passHist2;
}
public void setPassHist2(String passHist2) {
this.passHist2 = passHist2;
}
public String getPassHist3() {
return this.passHist3;
}
public void setPassHist3(String passHist3) {
this.passHist3 = passHist3;
}
public String getPassHist4() {
return this.passHist4;
}
public void setPassHist4(String passHist4) {
this.passHist4 = passHist4;
}
));
result = 37 * result
+ (getPasswd() == null ? 0 : this.getPasswd().hashCode());
result = 37 * result
+ (getPassHist1() == null ? 0 : this.getPassHist1().hashCode());
result = 37 * result
+ (getPassHist2() == null ? 0 : this.getPassHist2().hashCode());
result = 37 * result
+ (getPassHist3() == null ? 0 : this.getPassHist3().hashCode());
result = 37 * result
+ (getPassHist4() == null ? 0 : this.getPassHist4().hashCode());
return result;
}
}
Please take note that i had several columns in tblUser of Timestamp data type.which were mapped in autogenerated hbm.xml and auto generated pojo as Serializable and because of that i was getting 'Could not deserialize Error'.later to fix that i replaced it manually with timestamp and in pojos with java.sql.Timestamp. I am using jdk 6.
i have two doubts:-
1.what could be the possible cause for this?
2.And why does it take a lot of time ,around almost 20 seconds,to create factory object.
thank you
P.S
I skipped posting TblUser.java which had just one property ,an object of TbluserId class.
Can you check the query present in the java code there is one field 'a.id.id' called. This must be the issue.

Categories

Resources