Mapping and POJO class creation for a database view in hibernate - java

Hai all I am using hibernate and Microsoft SQL server.
I have a view in my database as follows
create view [dbo].[Pat_Det] As Select patientid As pid,title, fname, mname,lname,dob,gender,mstatus,idtype,idno,mtongue,emailid,smsstatus,mailstatus,status,regcenter,regdate from dbo.LAB_patientreg WHERE 1=1
For this view I had created a Pojo class like this
package POJO;
import java.io.Serializable;
import java.util.Date;
public class AddressViewPojo implements Serializable{
String pid, title, fname, mname, lname, sex, mstatus, idtype, aadhar_no, emailid, regcenter;
Date dob, date_created;
int allow_sms, allow_email, status;
public String getPid() {
return pid;
}
public void setPid(String pid) {
this.pid = pid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getMname() {
return mname;
}
public void setMname(String mname) {
this.mname = mname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getMstatus() {
return mstatus;
}
public void setMstatus(String mstatus) {
this.mstatus = mstatus;
}
public String getIdtype() {
return idtype;
}
public void setIdtype(String idtype) {
this.idtype = idtype;
}
public String getAadhar_no() {
return aadhar_no;
}
public void setAadhar_no(String aadhar_no) {
this.aadhar_no = aadhar_no;
}
public String getEmailid() {
return emailid;
}
public void setEmailid(String emailid) {
this.emailid = emailid;
}
public String getRegcenter() {
return regcenter;
}
public void setRegcenter(String regcenter) {
this.regcenter = regcenter;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Date getDate_created() {
return date_created;
}
public void setDate_created(Date date_created) {
this.date_created = date_created;
}
public int getAllow_sms() {
return allow_sms;
}
public void setAllow_sms(int allow_sms) {
this.allow_sms = allow_sms;
}
public int getAllow_email() {
return allow_email;
}
public void setAllow_email(int allow_email) {
this.allow_email = allow_email;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
and Mapping file like this
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping auto-import="true" default-lazy="false">
<class name="POJO.AddressViewPojo" table="Pat_Det">
<property name="aadhar_no" column="aadhar_no"></property>
<property name="allow_email" column="allow_email"></property>
<property name="allow_sms" column="allow_sms"></property>
<property name="date_created" column="date_created"></property>
<property name="dob" column="dob"></property>
<property name="emailid" column="emailid"></property>
<property name="fname" column="emailid"></property>
<property name="idtype" column="idtype"></property>
<property name="lname" column="lname"></property>
<property name="mname" column="mname"></property>
<property name="mstatus" column="mstatus"></property>
<property name="pid" column="pid"></property>
<property name="regcenter" column="regcenter"></property>
<property name="sex" column="sex"></property>
<property name="status" column="status"></property>
<property name="title" column="title"></property>
</class>
</hibernate-mapping>
But when I am validating the Mapping file an error occurs like this
XML validation started.
Checking file:/E:/akshai/TREVALAB/src/MAPPING/AddressViewPojo.hbm.xml...
The content of element type "class" must match "(meta*,subselect?,cache?,synchronize*,comment?,tuplizer*,(id|composite-id),discriminator?,natural-id?,(version|timestamp)?,(property|many-to-one|one-to-one|component|dynamic-component|properties|any|map|set|list|bag|idbag|array|primitive-array)*,((join*,subclass*)|joined-subclass*|union-subclass*),loader?,sql-insert?,sql-update?,sql-delete?,filter*,resultset*,(query|sql-query)*)". [21]
XML validation finished.
Can anyone help me to solve out this issue.
Thanks in advance.

Your mapping absolutely needs an id. I guess PID is your id so you should write something like this :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping auto-import="true" default-lazy="false">
<class name="POJO.AddressViewPojo" table="Pat_Det">
<id name="pid" column="pid"></id> <!-- Right here -->
<property name="aadhar_no" column="aadhar_no"></property>
<property name="allow_email" column="allow_email"></property>
<property name="allow_sms" column="allow_sms"></property>
<property name="date_created" column="date_created"></property>
<property name="dob" column="dob"></property>
<property name="emailid" column="emailid"></property>
<property name="fname" column="emailid"></property>
<property name="idtype" column="idtype"></property>
<property name="lname" column="lname"></property>
<property name="mname" column="mname"></property>
<property name="mstatus" column="mstatus"></property>
<property name="regcenter" column="regcenter"></property>
<property name="sex" column="sex"></property>
<property name="status" column="status"></property>
<property name="title" column="title"></property>
</class>
</hibernate-mapping>

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" />

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" ?

auto database creation in hibernate with mysql

this is my code, where i done mistake. while running Test.java am getting error like "The requested resource is not available". i kept all this files in same package
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/studentdb </property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="connection.pool_size"> 1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<!-- List of XML mapping files -->
<mapping resource="student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Test.java
public class Test {
public static void main(String[] args) {
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
cfg.buildSessionFactory();
}
}
student.hbm.xml
<hibernate-mapping>
<class name="com.javathub.Student" table="stu_details">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="branch"></property>
<property name="fee"></property>
</class>
</hibernate-mapping>
Student.java
public class Student {
private int id;
private String name;
private String branch;
private double fee;
public Student(){
}
public Student(int id, String name, String branch, double fee) {
super();
this.id = id;
this.name = name;
this.branch = branch;
this.fee = fee;
}
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;
}
public String getBranch() {
return branch;
}
public void setBranch(String branch) {
this.branch = branch;
}
public double getFee() {
return fee;
}
public void setFee(double fee) {
this.fee = fee;
}
}
please help me, thanks in advance
keep the student.hbm.xml and hibernate.cfg.xml in src folder not in package and run again.

access a component property in hibernate

I have three classes
Student.java
public class Student {
long id;
String name;
Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
}
Address.java
public class Address {
String houseNumber;
String addrLine1;
String addrLine2;
String phone;
public String getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(String houseNumber) {
this.houseNumber = houseNumber;
}
public String getAddrLine1() {
return addrLine1;
}
public void setAddrLine1(String addrLine1) {
this.addrLine1 = addrLine1;
}
public String getAddrLine2() {
return addrLine2;
}
public void setAddrLine2(String addrLine2) {
this.addrLine2 = addrLine2;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Hibernate Mapping for Student.hbm.xml
Student.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="Student" table="STUDENT">
<id name="id" type="long" column="ID"/>
<property name="name" column="NAME"/>
<component name="address" class="Address">
<property name="houseNumber" column="HOUSE_NUMBER" not-null="true"/>
<property name="addrLine1" column="ADDRLINE1"/>
<property name="addrLine2" column="ADDRLINE2"/>
<property name="phone" column="PHONE"/>
</component>
</component>
</class>
</hibernate-mapping>
Now I want to access the property houseNumber, phone using detached criteria
but when I try to get the property as address.phone
I get the errors as
org.hibernate.QueryException: could not resolve property: phone of: Student
The error occurs because Student really does not have the "phone", which is a Address property.
The correct usage should be something like session.createCriteria( Student.class ).add( Restrictions.eq( "address.phone", "myPhoneNumber" ) ).list() for common criterias.
The version with DetachedCriteria is
DetachedCriteria criteria = DetachedCriteria.forClass( Student.class ).add(Restrictions.eq( "address.phone", "99999999" ) );
List students = criteria.getExecutableCriteria( session ).list();

Exception in thread "main" org.hibernate.MappingException: invalid configuration

Hi Iam trying to run my hiberanate application i am getting the Hibernate Exception.
my hibernate.cfg.xml file is
<?xml version='1.0' encoding='UTF-8'?>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect </property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">root</property>
<property name="connection.password">mysql</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- <mapping resource="config\\hibernate.hbm.xml"/ -->
<mapping resource="config\\employee.hbm.xml"/>>
</session-factory>
employee.hbm.xml
<?xml version='1.0' encoding='UTF-8'?>
<hibernate-mapping>
<class name = "com.javatpoint.mypackage.Employee" table = "emp_TPCH" discriminator-value="emp">
<id name = "id">
<generator class = "increment">
</generator>
</id>
<discriminator column="type" type= "string"></discriminator>
<property name ="Name"></property>
<subclass name = "com.javatpoint.mypackage.Regular_Employee" discriminator-value="reg_emp">
<property name = "salary"></property>
<property name = "bonus"></property>
</subclass>
<subclass name = "com.javatpoint.mypackage.Contract_Employee" discriminator-value = "con_emp">
<property name = "pay_Per_Hour"></property>
<property name = "contact_Duration"></property>
</subclass>
</class>
</hibernate-mapping>
Employee.java is
package com.javatpoint.mpackage;
public class Employee {
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;
}
}
Contract_Employee.java
package com.javatpoint.mpackage;
public class Contract_Employee extends Employee {
private float pay_Per_Hour;
private String contact_Duration;
public float getPay_Per_Hour() {
return pay_Per_Hour;
}
public void setPay_Per_Hour(float pay_Per_Hour) {
this.pay_Per_Hour = pay_Per_Hour;
}
public String getContact_Duration() {
return contact_Duration;
}
public void setContact_Duration(String contact_Duration) {
this.contact_Duration = contact_Duration;
}
}
Regular Employee.js is
package com.javatpoint.mpackage;
public class Regular_Employee extends Employee {
private float salary;
private int bonus;
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
public int getBonus() {
return bonus;
}
public void setBonus(int bonus) {
this.bonus = bonus;
}
}
Guys please help me to come out of this Exception.
Include this as the second line in your file:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
There are maybe other errors, but this line is invalid:
<mapping resource="config\\employee.hbm.xml"/>>
^-- two brackets here
Also, the resource should be config/employee.hbm.xml. The resource is a classpath resource, using forward slashes as path separator.

Categories