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" />
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>.
How to resolve this issue org.hibernate.AssertionFailure: null id in com.xxxxxx.Profiles entry (don't flush the Session after an exception occurs)
I'm using hibernate and Mysql, I want to insert the data into a table of my database but I was unable to do it.
Thanks.
This is my Dao:
public class ProfilesDao {
public void addProfile(Profiles profile){
Transaction tx = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try{
tx = session.beginTransaction();
session.save(profile);
session.getTransaction().commit();
} catch (Exception e){
e.printStackTrace();
if(tx != null){
tx.rollback();
}
} finally {
session.flush();
session.close();
}
}
}
This is my Bean:
public void addProfile(){
Profiles profiles = new Profiles(getProfileName(),getProfileDescription());
ProfilesDao profilesDao = new ProfilesDao();
profilesDao.addProfile(profiles);
}
This is my POJO:
#Entity
#Table(name="profiles"
,catalog="metaestudiante_project_v1"
, uniqueConstraints = #UniqueConstraint(columnNames="profile_name")
)
public class Profiles implements java.io.Serializable {
private Short profileId;
private String profileName;
private String profileDescription;
private Set userses = new HashSet(0);
public Profiles() {
}
public Profiles(String profileName, String profileDescription) {
this.profileName = profileName;
this.profileDescription = profileDescription;
}
public Profiles(String profileName, String profileDescription, Set userses) {
this.profileName = profileName;
this.profileDescription = profileDescription;
this.userses = userses;
}
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="profile_id", unique=true, nullable=false)
public Short getProfileId() {
return this.profileId;
}
public void setProfileId(Short profileId) {
this.profileId = profileId;
}
#Column(name="profile_name", unique=true, nullable=false, length=15)
public String getProfileName() {
return this.profileName;
}
public void setProfileName(String profileName) {
this.profileName = profileName;
}
#Column(name="profile_description", nullable=false, length=140)
public String getProfileDescription() {
return this.profileDescription;
}
public void setProfileDescription(String profileDescription) {
this.profileDescription = profileDescription;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="profiles")
public Set getUserses() {
return this.userses;
}
public void setUserses(Set userses) {
this.userses = userses;
}
}
And this is my hbm.xml
<hibernate-mapping>
<class name="com.besolapp.model.pojos.Profiles" table="profiles" catalog="metaestudiante_project_v1" optimistic-lock="version">
<id name="profileId" type="java.lang.Byte">
<column name="profile_id" />
<generator class="identity" />
</id>
<property name="profileName" type="string">
<column name="profile_name" length="15" not-null="true" unique="true" />
</property>
<property name="profileDescription" type="string">
<column name="profile_description" length="140" not-null="true" />
</property>
<set name="userses" table="users" inverse="true" lazy="true" fetch="select">
<key>
<column name="profile_id" not-null="true" />
</key>
<one-to-many class="com.besolapp.model.pojos.Users" />
</set>
</class>
</hibernate-mapping>
All this looks like easy but I am getting an error:
org.hibernate.AssertionFailure: null id in com.besolapp.model.pojos.Profiles entry (don't flush the Session after an exception occurs)
Can anybody help me please?
As I run my main class (Runner) program I get the following exception :
org.hibernate.id.IdentifierGenerationException: attempted to assign id
from null one-to-one property: country
I don't know the reason, why am I getting this exception.
The mapping xml :
<hibernate-mapping>
<class name="pojo.Country" table="country">
<id name="countryID" column="c_id">
<generator class="increment" />
</id>
<property name="countryName" column="c_name" />
<one-to-one class="pojo.PM" name="pm" cascade="all" />
</class>
<class name="pojo.PM" table="pm">
<id name="countryID" column="c_id">
<generator class="foreign">
<param name="property">country</param>
</generator>
</id>
<property name="pmName" column="pm_name" />
<one-to-one class="pojo.Country" name="country" constrained="true" />
</class>
</hibernate-mapping>
POJO Classes :
Country
public class Country {
private int countryID;
private String countryName;
private PM pm;
public PM getPm() {
return pm;
}
public void setPm(PM pm) {
this.pm = pm;
}
public int getCountryID() {
return countryID;
}
public void setCountryID(int countryID) {
this.countryID = countryID;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
PM
public class PM {
private int countryID;
private String pmName;
private Country country;
public int getCountryID() {
return countryID;
}
public void setCountryID(int countryID) {
this.countryID = countryID;
}
public String getPmName() {
return pmName;
}
public void setPmName(String pmName) {
this.pmName = pmName;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
}
and this is the class that tries to commit the transaction :
public class Runner {
public static void main(String args[]) {System.out.println("dfdf");
Configuration config = new Configuration().configure();
SessionFactory sessFact = config.buildSessionFactory();
Session session = sessFact.openSession();
Transaction trans = session.beginTransaction();
Country c = new Country();
PM pm = new PM();
pm.setPmName("Manmohan Singh");
c.setCountryName("India");
c.setPm(pm);
session.save(c);
trans.commit();
}
}
SQL that created table :
CREATE TABLE country(c_id INTEGER,c_name TEXT,PRIMARY KEY(c_id));
CREATE TABLE pm(c_id INTEGER,pm_name TEXT);
The problem is the country variable. You should initialize all the attirbutes before trying to do some transactions.
EDIT: In your Hibernate file, you want to generate the PM ID from the ID of the country property. However, this property has never been initialized.
<class name="pojo.PM" table="pm">
<id name="countryID" column="c_id">
<generator class="foreign">
<param name="property">country</param>
</generator>
</id>
<property name="pmName" column="pm_name" />
<one-to-one class="pojo.Country" name="country" constrained="true" />
</class>
So, add pm.setCountry(c); to your code.
i am new in using hibernate and for some reason i am getting a list of null objects when i am using the following code:
public static void main(String args[])
{
Session s = HibernateUtil.currentSession();
ArrayList lst = (ArrayList) s.createQuery("from Users").list();
for(Object obj : lst){
Users user = (Users)obj;
System.Out.println(user.getUserid()); // null
}
}
my hibernate mapping xml looks like this:
<?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 27, 2012 9:48:45 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="us.Users" table="USERS">
<id name="userid" type="int">
<column name="USERID" precision="9" scale="0" />
<generator class="assigned" />
</id>
<property name="username" type="string">
<column name="USERNAME" length="200" />
</property>
<property name="password" type="string">
<column name="PASSWORD" length="200" />
</property>
<property name="firstName" type="string">
<column name="FIRST_NAME" length="200" />
</property>
<property name="lastName" type="string">
<column name="LAST_NAME" length="200" />
</property>
<property name="dateOfBirth" type="timestamp"> // my guess was that the problem appears with the timestamp property
<column name="DATE_OF_BIRTH" />
</property>
<property name="registrationDate" type="timestamp">
<column name="REGISTRATION_DATE" />
</property>
<one-to-one name="administrators" class="assignment2.Administrators"></one-to-one>
<set name="histories" table="HISTORY" inverse="true" lazy="false" fetch="select">
<key>
<column name="USERID" precision="9" scale="0" not-null="true" />
</key>
<one-to-many class="us.History" />
</set>
<set name="loginlogs" table="LOGINLOG" inverse="true" lazy="false" fetch="select">
<key>
<column name="USERID" precision="9" scale="0" not-null="true" />
</key>
<one-to-many class="us.Loginlog" />
</set>
</class>
here is my hibernate.cfg.xml :
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">abcd</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">SYSTEM</property>
<property name="hibernate.default_schema">SYSTEM</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.search.autoregister_listeners">false</property>
<mapping resource="assignment2/History.hbm.xml" />
<mapping resource="assignment2/Similarity.hbm.xml" />
<mapping resource="assignment2/Loginlog.hbm.xml" />
<mapping resource="assignment2/Users.hbm.xml" />
<mapping resource="assignment2/Administrators.hbm.xml" />
<mapping resource="assignment2/Mediaitems.hbm.xml" />
</session-factory>
and the users class:
/**
* Users generated by hbm2java
*/
public class Users implements java.io.Serializable {
private int userid;
private String username;
private String password;
private String firstName;
private String lastName;
private Date dateOfBirth;
private Date registrationDate;
private Administrators administrators;
private Set<History> histories = new HashSet<History>(0);
private Set<Loginlog> loginlogs = new HashSet<Loginlog>(0);
public Users() {
}
public Users(int userid) {
this.userid = userid;
}
public Users(int userid, String username, String password,
String firstName, String lastName, Serializable dateOfBirth,
Serializable registrationDate, Administrators administrators,
Set<History> histories, Set<Loginlog> loginlogs) {
this.userid = userid;
this.username = username;
this.password = password;
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
this.registrationDate = registrationDate;
this.administrators = administrators;
this.histories = histories;
this.loginlogs = loginlogs;
}
public int getUserid() {
return this.userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
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 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 Date getDateOfBirth() {
return this.dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public Date getRegistrationDate() {
return this.registrationDate;
}
public void setRegistrationDate(Date registrationDate) {
this.registrationDate = registrationDate;
}
public Administrators getAdministrators() {
return this.administrators;
}
public void setAdministrators(Administrators administrators) {
this.administrators = administrators;
}
public Set<History> getHistories() {
return this.histories;
}
public void setHistories(Set<History> histories) {
this.histories = histories;
}
public Set<Loginlog> getLoginlogs() {
return this.loginlogs;
}
public void setLoginlogs(Set<Loginlog> loginlogs) {
this.loginlogs = loginlogs;
}
}
thanks alot in advance