Hibernate mapping and query - java

The hibernate mapping of my hbm.xml is:
<class name="UserCalendar" table="user_calendar">
<id name="userCalendarId" column="user_calendar_id" type="long">
<generator class="native" />
</id>
<property name="userId" column="user_id" type="long" not-null="true"/>
<property name="userLoginName" column="user_login_name" type="string" not-null="true" length="32000" />
<property name="userName" column="user_name" type="string" not-null="true" length="32000" />
<list name="userDates" cascade="all" lazy="false">
<key column="user_calendar_id"/>
<index column="idx"/>
<one-to-many class="UserDate"/>
</list>
</class>
<class name="UserDate" table="user_date">
<id name="userDateId" column="user_date_id" type="long">
<generator class="native" />
</id>
<property name="date" column="date" type="date"/>
<list name="userItems" cascade="all" lazy="false">
<key column="user_date_id"/>
<index column="idx"/>
<one-to-many class="UserItem"/>
</list>
</class>
<class name="UserItem" table="user_item">
<id name="userItemId" column="user_item_id" type="long">
<generator class="native"/>
</id>
<property name="spaceId" column="space_id" type="long"/>
<property name="spaceName" column="space_name" type="string"/>
<property name="itemRefId" column="item_ref_id" type="string"/>
<property name="itemId" column="item_id" type="long"/>
<property name="allocation" column="allocation" type="double"/>
<property name="scheduledStrategy" column="scheduled_strategy" type="integer"/>
<property name="utilization" column="utilization" type="double"/>
<property name="deadline" column="deadline" type="date"/>
<property name="ticketType" column="ticket_type" type="integer"/>
<property name="isCurrentlyAssigned" column="is_currently_assigned" type="boolean"/>
</class>
The UserCalendar.java:
public class UserCalendar implements Serializable {
private static final long serialVersionUID = 10172L;
private long userCalendarId;
private long userId;
private String userLoginName;
private String userName;
private List<UserDate> userDates;
public UserCalendar() {
}
public long getUserCalendarId() {
return userCalendarId;
}
public void setUserCalendarId(long userCalendarId) {
this.userCalendarId = userCalendarId;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserLoginName() {
return userLoginName;
}
public void setUserLoginName(String userLoginName) {
this.userLoginName = userLoginName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public List<UserDate> getUserDates() {
return userDates;
}
public void setUserDates(List<UserDate> userDates) {
this.userDates = userDates;
}
}
The UserDate.java:
public class UserDate implements Serializable {
private static final long serialVersionUID = 10173L;
private long userDateId;
private Date date;
private List<UserItem> userItems;
public UserDate() {
}
public long getUserDateId() {
return userDateId;
}
public void setUserDateId(long userDateId) {
this.userDateId = userDateId;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
public List<UserItem> getUserItems() {
return userItems;
}
public void setUserItems(List<UserItem> userItems) {
this.userItems = userItems;
}
}
And the UserItem.java:
public class UserItem implements Serializable {
private static final long serialVersionUID = 10174L;
public static final int AUTO = 1;
public static final int EQUAL = 2;
public static final int CUSTOM = 3;
public static final int CUSTOM_EQUAL = 4;
public static final int GENERAL_TICKET = 5;
public static final int SPECIAL_TICKET_HALF = 6;
public static final int SPECIAL_TICKET_FULL = 7;
private long userItemId;
private long spaceId;
private String spaceName;
private long itemId;
private String itemRefId;
private double allocation;
private int scheduledStrategy;
private double utilization;
private Date deadline;
private int ticketType;
private boolean isCurrentlyAssigned;
public UserItem() {
}
public long getUserItemId() {
return userItemId;
}
public void setUserItemId(long userItemId) {
this.userItemId = userItemId;
}
public long getSpaceId() {
return spaceId;
}
public void setSpaceId(long spaceId) {
this.spaceId = spaceId;
}
public long getItemId() {
return itemId;
}
public void setItemId(long itemId) {
this.itemId = itemId;
}
public double getAllocation() {
return allocation;
}
public void setAllocation(double allocation) {
this.allocation = allocation;
}
public int getScheduledStrategy() {
return scheduledStrategy;
}
public void setScheduledStrategy(int scheduledStrategy) {
this.scheduledStrategy = scheduledStrategy;
}
public double getUtilization() {
return utilization;
}
public void setUtilization(double utilization) {
this.utilization = utilization;
}
public Date getDeadline() {
return deadline;
}
public void setDeadline(Date deadline) {
this.deadline = deadline;
}
public int getTicketType() {
return ticketType;
}
public void setTicketType(int ticketType) {
this.ticketType = ticketType;
}
public String getSpaceName() {
return spaceName;
}
public void setSpaceName(String spaceName) {
this.spaceName = spaceName;
}
public String getItemRefId() {
return itemRefId;
}
public void setItemRefId(String itemRefId) {
this.itemRefId = itemRefId;
}
public boolean isCurrentlyAssigned() {
return isCurrentlyAssigned;
}
public void setCurrentlyAssigned(boolean isCurrentlyAssigned) {
this.isCurrentlyAssigned = isCurrentlyAssigned;
}
}
Now I want to select those UserCalendar object which has a specific itemId. In my thought if I insert userCalendarId in UserItem and execute
SELECT USERCALENDAR
FROM USER_CALENDAR
WHERE USERCALENDAR.USERCALENDARID IN
(SELECT USERCALENDARID
FROM USERITEM
WHERE USERITEM.ITEMID=ID)
then it might be possible.
Am I right?
How can I insert userCalendarId in UserItem? What is the mapping needed for this?
Thanks and regards.

To have one-to-many you will need column in UserDate that refers to UserCalendar.userCalendarId and column in UserItem to refer to UserDate.userDateId. You will need to specify those columns via many-to-one in those classes.
Then you can use join
SELECT * FROM user_calendar uc
JOIN user_date ud ON ud.user_calendar_id=uc.user_calendar_id
JOIN user_item ui ON ui.user_date_id=ud.user_date_id
WHERE ui.user_item_id=<your value>
Assuming that you have those new columns user_calendar_id and user_date_id in user_date and user_item.
In HQL it will be simpler but I don't remember on top of my head. Check docs.
It could be something like
select ui.userDate.userCaledar from UserItem ui where ui.userItemId=:id
Provided that you added properties userDate and userCalendar via many-to-one

Related

Repeated column in mapping for entity: BatchJobConfig column: BATCH_JOB_CONFIG_ID (should be mapped with insert="false" update="false")

I'm calling createSession method in Main method.
private static void createSession() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
SessionFactory fact = meta.getSessionFactoryBuilder().build();
Session ss = factory.openSession();
Transaction tt = session.beginTransaction();
BatchJobConfig config = new BatchJobConfig();
BatchJobConfigDetails details = new BatchJobConfigDetails();
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
System.out.println("timestamp -> "+timestamp);
BatchJobConfigDetails batchJobConfigDtl = new BatchJobConfigDetails(300, 3, "JAVA", date, "JAVA", date, "N",
"Some Key", "Some value", "FT", "KEY DESCRIPTION", "Y");
try {
config.setBatchJobConfigDtl(batchJobConfigDtl);
config.setAddUserCd("gdfdgdfgdgd");
config.setBatchJobConfigId(505);
config.setActiveInd("YYYY");
config.setAddUserDtm(timestamp);
config.setDeleteInd("N");
config.setEndDtm(timestamp);
config.setJobDesc("DESCRIPTION");
config.setJobNm("JOB NAME");
config.setJobType("Job Type");
config.setLastUpdtDtm(timestamp);
config.setLastUpdtUserCd("someone");
config.setStatus("COMPLETED");
config.setStartDtm(timestamp);
ss.save(config);
tt.commit();
System.out.println("config session saved");
} catch (HibernateException exception) {
System.out.println("Problem creating session factory!!!!!!!!!!");
exception.printStackTrace();
} finally {
fact.close();
ss.close();
}
try {
details.setAddUserCd("fffffffffffffffffffff");
details.setAddUserDtm(timestamp);
details.setBusinessUpdtInd("dssssssss");
details.setDeleteInd("NNNNNNNNN");
details.setKeyDataType("ggggggggggggg");
details.setKeyDesc("Description.......");
details.setKeyNm("some key name");
details.setKeyVal("someval");
details.setLastUpdtDtm(timestamp);
details.setLastUpdtUserCd("last user");
BatchJobConfig batchJobConfig = new BatchJobConfig(1L, "JAVA", date, "C#", date, "N", "MissingCK",
"JOB DESCRIPTION", "FT", date, date, "COMPLETED", "Y");
List<BatchJobConfig> b = null;
b.add(batchJobConfig);
details.setBatchJobConfigs(b);
session.save(details);
t.commit();
System.out.println("details session saved");
} catch (HibernateException exception) {
System.out.println("Problem creating session factory....");
exception.printStackTrace();
} finally {
factory.close();
session.close();
}
}
I have the following two Entities.
BatchJobConfig.java
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import javax.persistence.*;
/**
* The persistent class for the BATCH_JOB_CONFIG database table.
*
*/
#Entity
#Table(name="BATCH_JOB_CONFIG")
#NamedQuery(name="BatchJobConfig.findAll", query="SELECT b FROM BatchJobConfig b")
public class BatchJobConfig implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="BATCH_JOB_CONFIG_ID")
private long batchJobConfigId;
#Column(name="ADD_USER_CD")
private String addUserCd;
#Column(name="ADD_USER_DTM")
private Timestamp addUserDtm;
#Column(name="LAST_UPDT_USER_CD")
private String lastUpdtUserCd;
#Column(name="LAST_UPDT_DTM")
private Timestamp lastUpdtDtm;
#Column(name="DELETE_IND")
private String deleteInd;
#Column(name="JOB_NM")
private String jobNm;
#Column(name="JOB_DESC")
private String jobDesc;
#Column(name="JOB_TYPE")
private String jobType;
#Column(name="START_DTM")
private Timestamp startDtm;
#Column(name="END_DTM")
private Timestamp endDtm;
#Column(name="STATUS")
private String status;
#Column(name="ACTIVE_IND")
private String activeInd;
public Timestamp getAddUserDtm() {
return addUserDtm;
}
public void setAddUserDtm(Timestamp addUserDtm) {
this.addUserDtm = addUserDtm;
}
public String getLastUpdtUserCd() {
return lastUpdtUserCd;
}
public void setLastUpdtUserCd(String lastUpdtUserCd) {
this.lastUpdtUserCd = lastUpdtUserCd;
}
public Timestamp getLastUpdtDtm() {
return lastUpdtDtm;
}
public void setLastUpdtDtm(Timestamp lastUpdtDtm) {
this.lastUpdtDtm = lastUpdtDtm;
}
public String getDeleteInd() {
return deleteInd;
}
public void setDeleteInd(String deleteInd) {
this.deleteInd = deleteInd;
}
public String getJobNm() {
return jobNm;
}
public void setJobNm(String jobNm) {
this.jobNm = jobNm;
}
public String getJobDesc() {
return jobDesc;
}
public void setJobDesc(String jobDesc) {
this.jobDesc = jobDesc;
}
public String getJobType() {
return jobType;
}
public void setJobType(String jobType) {
this.jobType = jobType;
}
public Timestamp getStartDtm() {
return startDtm;
}
public void setStartDtm(Timestamp startDtm) {
this.startDtm = startDtm;
}
public Timestamp getEndDtm() {
return endDtm;
}
public void setEndDtm(Timestamp endDtm) {
this.endDtm = endDtm;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getActiveInd() {
return activeInd;
}
public void setActiveInd(String activeInd) {
this.activeInd = activeInd;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
//bi-directional many-to-one association to BatchJobConfigDtl
#ManyToOne
#JoinColumn(name="BATCH_JOB_CONFIG_ID", referencedColumnName="BATCH_JOB_CONFIG_ID")
private BatchJobConfigDetails batchJobConfigDtl;
public BatchJobConfig() {
}
public BatchJobConfig(long l, String string, Date date, String string2, Date date2, String string3, String string4,
String string5, String string6, Date date3, Date date4, String string7, String string8) {
// TODO Auto-generated constructor stub
}
public long getBatchJobConfigId() {
return this.batchJobConfigId;
}
public void setBatchJobConfigId(long batchJobConfigId) {
this.batchJobConfigId = batchJobConfigId;
}
public String getAddUserCd() {
return this.addUserCd;
}
public void setAddUserCd(String addUserCd) {
this.addUserCd = addUserCd;
}
public BatchJobConfigDetails getBatchJobConfigDtl() {
return this.batchJobConfigDtl;
}
public void setBatchJobConfigDtl(BatchJobConfigDetails batchJobConfigDtl) {
this.batchJobConfigDtl = batchJobConfigDtl;
}
}
BatchJobConfigDetails.java
import java.io.Serializable;
import javax.persistence.*;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
/**
* The persistent class for the BATCH_JOB_CONFIG_DTLS database table.
*
*/
#Entity
#Table(name = "BATCH_JOB_CONFIG_DTLS")
#NamedQuery(name = "BatchJobConfigDtl.findAll", query = "SELECT b FROM BatchJobConfigDtl b")
public class BatchJobConfigDetails implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "BATCH_JOB_CONFIG_DTLS_ID")
private long batchJobConfigDtlsId;
#Column(name = "ADD_USER_CD")
private String addUserCd;
#Column(name = "ADD_USER_DTM")
private Timestamp addUserDtm;
#Column(name = "BUSINESS_UPDT_IND")
private String businessUpdtInd;
#Column(name = "DELETE_IND")
private String deleteInd;
#Column(name = "KEY_DATA_TYPE")
private String keyDataType;
#Column(name = "KEY_DESC")
private String keyDesc;
#Column(name = "KEY_NM")
private String keyNm;
#Column(name = "KEY_VAL")
private String keyVal;
#Column(name = "LAST_UPDT_DTM")
private Timestamp lastUpdtDtm;
#Column(name = "LAST_UPDT_USER_CD")
private String lastUpdtUserCd;
// bi-directional many-to-one association to BatchJobConfig
#OneToMany(mappedBy = "batchJobConfigDtl")
private List<BatchJobConfig> batchJobConfigs;
public BatchJobConfigDetails() {
}
public BatchJobConfigDetails(int i, int j, String string, Date date, String string2, Date date2, String string3,
String string4, String string5, String string6, String string7, String string8) {
// TODO Auto-generated constructor stub
}
public BatchJobConfigDetails(int i, BatchJobConfig config1, String string, Date date, String string2, Date date2,
String string3, String string4, String string5, String string6, String string7, String string8) {
// TODO Auto-generated constructor stub
}
public long getBatchJobConfigDtlsId() {
return this.batchJobConfigDtlsId;
}
public void setBatchJobConfigDtlsId(long batchJobConfigDtlsId) {
this.batchJobConfigDtlsId = batchJobConfigDtlsId;
}
public String getAddUserCd() {
return this.addUserCd;
}
public void setAddUserCd(String addUserCd) {
this.addUserCd = addUserCd;
}
public Timestamp getAddUserDtm() {
return this.addUserDtm;
}
public void setAddUserDtm(Timestamp addUserDtm) {
this.addUserDtm = addUserDtm;
}
public String getBusinessUpdtInd() {
return this.businessUpdtInd;
}
public void setBusinessUpdtInd(String businessUpdtInd) {
this.businessUpdtInd = businessUpdtInd;
}
public String getDeleteInd() {
return this.deleteInd;
}
public void setDeleteInd(String deleteInd) {
this.deleteInd = deleteInd;
}
public String getKeyDataType() {
return this.keyDataType;
}
public void setKeyDataType(String keyDataType) {
this.keyDataType = keyDataType;
}
public String getKeyDesc() {
return this.keyDesc;
}
public void setKeyDesc(String keyDesc) {
this.keyDesc = keyDesc;
}
public String getKeyNm() {
return this.keyNm;
}
public void setKeyNm(String keyNm) {
this.keyNm = keyNm;
}
public String getKeyVal() {
return this.keyVal;
}
public void setKeyVal(String keyVal) {
this.keyVal = keyVal;
}
public Timestamp getLastUpdtDtm() {
return this.lastUpdtDtm;
}
public void setLastUpdtDtm(Timestamp lastUpdtDtm) {
this.lastUpdtDtm = lastUpdtDtm;
}
public String getLastUpdtUserCd() {
return this.lastUpdtUserCd;
}
public void setLastUpdtUserCd(String lastUpdtUserCd) {
this.lastUpdtUserCd = lastUpdtUserCd;
}
public List<BatchJobConfig> getBatchJobConfigs() {
return this.batchJobConfigs;
}
public void setBatchJobConfigs(List<BatchJobConfig> batchJobConfigs) {
this.batchJobConfigs = batchJobConfigs;
}
public BatchJobConfig addBatchJobConfig(BatchJobConfig batchJobConfig) {
getBatchJobConfigs().add(batchJobConfig);
batchJobConfig.setBatchJobConfigDtl(this);
return batchJobConfig;
}
public BatchJobConfig removeBatchJobConfig(BatchJobConfig batchJobConfig) {
getBatchJobConfigs().remove(batchJobConfig);
batchJobConfig.setBatchJobConfigDtl(null);
return batchJobConfig;
}
}
batchJob.hbm.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="BatchJobConfig" table="BATCH_JOB_CONFIG">
<meta attribute="class-description">
This class contains the BATCH_JOB_CONFIG.
</meta>
<id name="batchJobConfigId" type="int" column="BATCH_JOB_CONFIG_ID">
<generator class="native" />
</id>
<property name="addUserCd" column="ADD_USER_CD" type="string" />
<property name="addUserDtm" column="ADD_USER_DTM" type="timestamp" />
<property name="lastUpdtUserCd" column="LAST_UPDT_USER_CD"
type="string" />
<property name="lastUpdtDtm" column="LAST_UPDT_DTM" type="timestamp" />
<property name="deleteInd" column="DELETE_IND" type="string" />
<property name="jobNm" column="JOB_NM" type="string" />
<property name="jobDesc" column="JOB_DESC" type="string" />
<property name="jobType" column="JOB_TYPE" type="string" />
<property name="startDtm" column="START_DTM" type="timestamp" />
<property name="status" column="STATUS" type="string" />
<property name="endDtm" column="END_DTM" type="timestamp" />
<property name="activeInd" column="ACTIVE_IND" type="string" />
<many-to-one name="BatchJobConfigDetails" column="BATCH_JOB_CONFIG_ID"
class="BatchJobConfigDetails" not-null="true" />
</class>
<class name="BatchJobConfigDetails" table="BATCH_JOB_CONFIG_DTLS">
<meta attribute="class-description">
This class contains the BATCH_JOB_CONFIG_DETAILS.
</meta>
<id name="batchJobConfigDtlsId" type="int" column="BATCH_JOB_CONFIG_DTLS_ID">
<generator class="native" />
</id>
<property name="batchJobConfigId" column="BATCH_JOB_CONFIG_ID"
type="int" />
<property name="addUserCd" column="ADD_USER_CD" type="string" />
<property name="addUserDtm" column="ADD_USER_DTM" type="timestamp" />
<property name="businessUpdtInd" column="BUSINESS_UPDT_IND"
type="int" />
<property name="deleteInd" column="DELETE_IND" type="string" />
<property name="keyDataType" column="KEY_DATA_TYPE" type="string" />
<property name="keyDesc" column="KEY_DESC" type="string" />
<property name="keyNm" column="KEY_NM" type="string" />
<property name="keyVal" column="KEY_VAL" type="string" />
<property name="lastUpdtDtm" column="LAST_UPDT_DTM" type="timestamp" />
<property name="lastUpdtUserCd" column="LAST_UPDT_USER_CD" type="string" />
</class>
</hibernate-mapping>
hibernate.cfg.xml
<!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="hibernate.dialect">org.hibernate.dialect.DB2Dialect</property>
<property name="hibernate.connection.driver_class">com.ibm.db2.jcc.DB2Driver</property>
<property name="hibernate.connection.url">jdbc:db2://sdfsfsd:5000df2/dsf</property>
<property name="hibernate.connection.username">sfs</property>
<property name="hibernate.connection.password">sfs</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="show_sql">true</property>
<mapping resource="batchJob.hbm.xml"/>
</session-factory>
</hibernate-configuration>
What does it mean by this error message and how do you solve it?
Exception in thread "main" org.hibernate.MappingException: Repeated column in mapping for entity: BatchJobConfig column: BATCH_JOB_CONFIG_ID (should be mapped with insert="false" update="false")
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:862)
at org.hibernate.mapping.PersistentClass.checkPropertyColumnDuplication(PersistentClass.java:880)
at org.hibernate.mapping.PersistentClass.checkColumnDuplication(PersistentClass.java:902)
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:634)
at org.hibernate.mapping.RootClass.validate(RootClass.java:267)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:347)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:466)
at com.hms.api.batch.job.config.StartBatchJobConfigApplication.createSession(StartBatchJobConfigApplication.java:67)
at com.hms.api.batch.job.config.StartBatchJobConfigApplication.main(StartBatchJobConfigApplication.java:34)
What does this error message mean?
if yes how did you resolve it? Please help me with issue.
I appreciate your responses in advance. Thank you!!!!!!!!!!!!!!
In your java code, change a name of many to one relation, to anything but the current:
#ManyToOne
#JoinColumn(name="BATCH_JOB_CONFIG_ID", referencedColumnName="BATCH_JOB_CONFIG_ID")
private BatchJobConfigDetails batchJobConfigDtl;
something like
#ManyToOne
#JoinColumn(name="MY_NEW_NAME", referencedColumnName="BATCH_JOB_CONFIG_ID")
private BatchJobConfigDetails batchJobConfigDtl;
and also change it in your hbm.xml file appropriately.
UPDATE:
Also, change a name of columns in your hbl.xml file. One second.
from
<many-to-one name="BatchJobConfigDetails" column="BATCH_JOB_CONFIG_ID"
class="BatchJobConfigDetails" not-null="true" />
to
<many-to-one name="BatchJobConfigDetails" column="MY_NEW_NAME"
class="BatchJobConfigDetails" not-null="true" />

Hibernate ERROR: HHH000091

I am new to hibernate. My goal is to get query results to an ArrayList but I keep getting the ERROR: HHH000091: Expected type: int, actual value: org.hibernate.collection.internal.PersistentSet
I strongly believe the problem is in my mapping, any help is appreciated.
Errors
ERROR: HHH000123: IllegalArgumentException in class: com.mycompany.mavenproject1.Medicamento, setter method of property: labJoin
Apr 07, 2017 10:23:10 AM org.hibernate.property.BasicPropertyAccessor$BasicSetter set
ERROR: HHH000091: Expected type: int, actual value: org.hibernate.collection.internal.PersistentSet
My HQL query:
from Medicamento as m left join from Laboratorio as l where l.codigoLab=m.codigoLab
Mapping XML:
<class name="com.mycompany.mavenproject1.Medicamento" table="MEDICAMENTO" schema="ADMINFARMACIA" optimistic-lock="version">
<id name="codigoMed" type="long">
<column name="CODIGO_MED" not-null="true"/>
<generator class="assigned" />
</id>
<property name="nombreComercial" type="string">
<column name="NOMBRE_COMERCIAL" length="100" not-null="true" />
</property>
<property name="codigoPrincipio" type="string">
<column name="CODIGO_PRINCIPIO" length="50" not-null="true" />
</property>
<property name="stockMinimo" type="java.lang.Integer">
<column name="STOCK_MINIMO" />
</property>
<property name="codigoLab" type="java.lang.Integer">
<column name="CODIGO_LAB" />
</property>
<property name="comentario" type="string">
<column name="COMENTARIO" length="1000" />
</property>
<property name="existencias" type="java.lang.Integer">
<column name="EXISTENCIAS"/>
</property>
<set name="labJoin" fetch="join">
<key column="CODIGO_LAB" />
<one-to-many class="com.mycompany.mavenproject1.Laboratorio"/>
</set>
</class>
Laboratorio.java:
public class Laboratorio implements java.io.Serializable{
private int codigoLab;
private String nombreLab;
public Laboratorio(){
}
public int getCodigoLab() {
return codigoLab;
}
public void setCodigoLab(int codigoLab) {
this.codigoLab = codigoLab;
}
public String getNombreLab() {
return nombreLab;
}
public void setNombreLab(String nombreLab) {
this.nombreLab = nombreLab;
}
}
Medicamento.java - in this one labJoin and labName are the fields on "Laboratorio" table
public class Medicamento implements java.io.Serializable{
private Long codigoMed;
private String nombreComercial;
private String codigoPrincipio;
private int stockMinimo;
private int codigoLab;
private String comentario;
private int existencias;
private int labJoin;
private String labName;
public Medicamento(){
}
public Long getCodigoMed() {
return codigoMed;
}
public void setCodigoMed(Long codigoMed) {
this.codigoMed = codigoMed;
}
public String getNombreComercial() {
return nombreComercial;
}
public void setNombreComercial(String nombreComercial) {
this.nombreComercial = nombreComercial;
}
public String getCodigoPrincipio() {
return codigoPrincipio;
}
public void setCodigoPrincipio(String codigoPrincipio) {
this.codigoPrincipio = codigoPrincipio;
}
public int getStockMinimo() {
return stockMinimo;
}
public void setStockMinimo(int stockMinimo) {
this.stockMinimo = stockMinimo;
}
public int getCodigoLab() {
return codigoLab;
}
public void setCodigoLab(int codigoLab) {
this.codigoLab = codigoLab;
}
public int getLabJoin() {
return labJoin;
}
public void setLabJoin(int labJoin) {
this.labJoin = labJoin;
}
public String getLabName() {
return labName;
}
public void setLabJoin(String labName) {
this.labName= labName;
}
public String getComentario() {
return comentario;
}
public void setComentario(String comentario) {
this.comentario = comentario;
}
public int getExistencias() {
return existencias;
}
public void setExistencias(int existencias) {
this.existencias = existencias;
}
}
Calling method
private void displayResult(List rl){
ArrayList<Object> oneRow = new ArrayList<Object>();
for (Object o: rl){
Medicamento medList = (Medicamento)o;
System.out.println(labList.getCodigoLab());
oneRow.add(medList.getCodigoMed());
oneRow.add(medList.getExistencias());
oneRow.add(medList.getNombreComercial());
oneRow.add(medList.getLabJoin());
}
LowStockTableModel model = new LowStockTableModel(oneRow);
try{
jTable1.setModel(model);
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e.getLocalizedMessage(),"Error",JOptionPane.ERROR_MESSAGE);
jTextField1.setText("");
}
}
In your mapping, you have this
<set name="labJoin" fetch="join">
<key column="CODIGO_LAB" />
<one-to-many class="com.mycompany.mavenproject1.Laboratorio"/>
</set>
But property labJoin has type int. The type of this property has to be Set<Laboratorio>.

Perform two save("entity-name",object) in a single session of hibernate?

I have a POJO class NewUniversity.java. I've created a mapping file for it viz. RegisterAction.hbm.xml. Now the problem is when I try to call the save methods from DAO class, only the first one gets executed, the second one doesn't. I've two tables linked to one entity through 'entity-mapping' attribute in the xml file.
File: NewUniversity.java
public class NewUniversity implements Serializable {
// University fields
private String uCode;
private String uName;
private String uAddress;
private String uCity;
private String uState;
private long uContactNo;
private String uEmail;
// University director fields
private String name;
private String address;
private String city;
private String state;
private long contactNo;
private String email;
private String userName;
private String pwd;
public String getuCode() {
return uCode;
}
public void setuCode(String uCode) {
this.uCode = uCode;
}
public String getuName() {
return uName;
}
public void setuName(String uName) {
this.uName = uName;
}
public String getuAddress() {
return uAddress;
}
public void setuAddress(String uAddress) {
this.uAddress = uAddress;
}
public String getuCity() {
return uCity;
}
public void setuCity(String uCity) {
this.uCity = uCity;
}
public String getuState() {
return uState;
}
public void setuState(String uState) {
this.uState = uState;
}
public long getuContactNo() {
return uContactNo;
}
public void setuContactNo(long uContactNo) {
this.uContactNo = uContactNo;
}
public String getuEmail() {
return uEmail;
}
public void setuEmail(String uEmail) {
this.uEmail = uEmail;
}
// University directors setters/getters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public long getContactNo() {
return contactNo;
}
public void setContactNo(long contactNo) {
this.contactNo = contactNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
File: RegisterAction.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">
<hibernate-mapping>
<class name="in.ryr.register.NewUniversity" table="university"
entity-name="university">
<id name="uCode" column="code" type="string">
<generator class="assigned" />
</id>
<property name="uName" column="name" />
<property name="uAddress" column="address" />
<property name="uCity" column="city" />
<property name="uState" column="state" />
<property name="uContactNo" column="contact_no" />
<property name="uEmail" column="email" />
<property name="userName" column="username" />
</class>
<class name="in.ryr.register.NewUniversity" table="university_director"
entity-name="uniDirector">
<id name="userName" column="username" type="string">
<generator class="assigned" />
</id>
<property name="name" column="name" />
<property name="address" column="address" />
<property name="city" column="city" />
<property name="state" column="state" />
<property name="contactNo" column="contact_no" />
<property name="email" column="email" />
<property name="pwd" column="password" />
<property name="uCode" column="u_code" />
</class>
</hibernate-mapping>
File: RegisterDAO.java
public void register(NewUniversity user) throws Exception {
session = factory.openSession();
transaction = session.beginTransaction();
try {
session.save("university", user); //This is working fine
session.save("uniDirector", user); //This doesn't execute at all
transaction.commit();
session.close();
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
session.close();
}
}
I've tried using persist() as well. But no luck!
The point is, when I perform it on two different sessions, it works perfectly. (All the objects value are coming through .jsp to struts). For some reasons I didn't use annotations.
Maybe it is because Session#save(entityName, object) method requires object to be a "transient" object (i.e. that has not already been persisted), and that, after the first call to session.save("university", user); then user is no more transient.
Persist the given transient instance, first assigning a generated
identifier. (Or using the current value of the identifier property if
the assigned generator is used.) This operation cascades to associated
instances if the association is mapped with cascade="save-update"
What happens when you make a get of your persisted "university" entity just after the first save, and then save it as "uniDirector" ?

hibernate dynamic component equivalent annotation

What is the equivalent way of defining dynamic component in hibernate by annotations?
public abstract class CustomizableEntity {
private Map customProperties;
public Map getCustomProperties() {
if (customProperties == null)
customProperties = new HashMap();
return customProperties;
}
public void setCustomProperties(Map customProperties) {
this.customProperties = customProperties;
}
public Object getValueOfCustomField(String name) {
return getCustomProperties().get(name);
}
public void setValueOfCustomField(String name, Object value) {
getCustomProperties().put(name, value);
}
}
my entity:
public class Contact extends CustomizableEntity {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
hibernate xml:
<hibernate-mapping auto-import="true" default-access="property" default-cascade="none" default-lazy="true">
<class abstract="false" name="com.enterra.customfieldsdemo.domain.Contact" table="tbl_contact">
<id column="fld_id" name="id">
<generator class="native"/>
</id>
<property name="name" column="fld_name" type="string"/>
<dynamic-component insert="true" name="customProperties" optimistic-lock="true" unique="false" update="true">
</dynamic-component>
</class>
</hibernate-mapping>
I want to use a dynamic-component by HashMap to create entities at runtime.
What is the equivalent way of defining dynamic component in hibernate by annotations?
http://www.infoq.com/articles/hibernate-custom-fields

Read data from table where primary key is composite using hibernate

I have these POJO classes in my project.
public class MerchantChainUser extends com.avanza.ni.common.dto.AbstractDTO
implements java.io.Serializable {
private long chainId;
private CompositePK compositePK;
public MerchantChainUser() {
}
public void setChainId(long chainId) {
this.chainId = chainId;
}
public long getChainId() {
return chainId;
}
public void setCompositePK(CompositePK compositePK) {
this.compositePK = compositePK;
}
public CompositePK getCompositePK() {
return compositePK;
}
}
AND
public class CompositePK implements Serializable {
private long merchantId;
private long userId;
public void setMerchantId(long merchantId) {
this.merchantId = merchantId;
}
public long getMerchantId() {
return merchantId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public long getUserId() {
return userId;
}
}
hbm.xml file for MerchantUserChain is
<hibernate-mapping>
<class name="com.avanza.ni.portal.dto.MerchantChainUser" table="MERCHANT_CHAIN_USER">
<composite-id name="compositePK">
<key-property name="merchantId" type="long" column="MERCHANT_ID"></key-property>
<key-property name="userId" type="long" column="MERCHANT_USER_ID"></key-property>
</composite-id>
<property name="chainId" type="long">
<column name="MERCHANT_CHAIN_ID" length="38" />
</property>
</class>
Now what i wanted is i have to read data from the table using just MERCHANT_USER_ID. I am able to retreive whole data from the table but now i want to set a criteria as Only give me those row that MERCHANT_USER_ID is specific. I didn't know how to write data criteria.
the answer that i put the comment has been deleted, so i post it here :D
Criteria crit = session.createCriteria(MerchantChainUser.class)
.add(Restrictions.eq("compositePK.userId", userId));
or with hql
session.createQuery("from MerchantChainUser where compositePK.userId = :userid").setParameter("userid",userid);
Can you try:
Criteria crit = session.createCriteria(MerchantChainUser.class);
crit.add(Restrictions.eq("compositePK.merchantId", 42));
crit.add(Restrictions.eq("compositePK.userId", 43));
crit.setMaxResults(10);
List result = crit.list();
Vinit

Categories