While trying to run the following program :
public class Runner {
public static void main(String args[]) {
Configuration config = new Configuration().configure();
SessionFactory sessFact = config.buildSessionFactory();
Session sess = sessFact.openSession();
Transaction trans = sess.beginTransaction();
Person p = new Person();
p.setPersonName("Suhail");
Set<String> set = new HashSet<String>();
set.add("Address-1");
set.add("Address-2");
set.add("Address-3");
p.setAddressSet(set);
sess.save(p);
trans.commit();
}
}
I am getting :
SEVERE: IllegalArgumentException in class: pojo.Address, getter method
of property: addressID
Exception in thread "main" org.hibernate.PropertyAccessException:
IllegalArgumentException occurred calling getter of pojo.Address.addressID
I don't know the reason for this. I am trying to make one to many association between Person and Address class.
mapping xml:
<hibernate-mapping>
<class name="pojo.Person" table="person">
<id name="personID" column="p_id">
<generator class="increment" />
</id>
<property name="personName" column="p_name" />
<set name="addressSet" table="address" cascade="all">
<key column="p_id" />
<one-to-many class="pojo.Address" />
</set>
</class>
<class name="pojo.Address" table="address">
<id name="addressID" column="a_id">
<generator class="increment" />
</id>
<property name="personAddress" column="p_address" />
</class>
</hibernate-mapping>
POJO:
Person
public class Person {
private int personID;
private String personName;
private Set addressSet;
public int getPersonID() {
return personID;
}
public void setPersonID(int personID) {
this.personID = personID;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public Set getAddressSet() {
return addressSet;
}
public void setAddressSet(Set addressSet) {
this.addressSet = addressSet;
}
}
Address
public class Address {
private int addressID;
private String personAddress;
public int getAddressID() {
return addressID;
}
public void setAddressID(int addressID) {
this.addressID = addressID;
}
public String getPersonAddress() {
return personAddress;
}
public void setPersonAddress(String personAddress) {
this.personAddress = personAddress;
}
}
SQL that created table
CREATE TABLE person(p_id INTEGER,p_name TEXT,PRIMARY KEY(p_id));
CREATE TABLE address(a_id INTEGER,p_address TEXT);
In your example you add to adress set Strings. But in your configuration you specify Address class.So I think your problem in this lines:
Set<String> set = new HashSet<String>();
set.add("Address-1");
set.add("Address-2");
set.add("Address-3");
You need to change set to Set<Address> and add Address objects in set:
Set<Address> set = new HashSet<>();
Address address = new Address();
address.setPersonAddress("Address-1");
set.add(address);
You can do couple of things without Mapping xml file. Place #Embeddable on ur Pojo of
#Embeddable
#Entity
public class Address {
#Id
private int addressID;
private String personAddress;
public int getAddressID() {
return addressID;
}
public void setAddressID(int addressID) {
this.addressID = addressID;
}
public String getPersonAddress() {
return personAddress;
}
public void setPersonAddress(String personAddress) {
this.personAddress = personAddress;
}
}
Then on
public class Runner {
public static void main(String args[]) {
Configuration config = new Configuration().configure();
SessionFactory sessFact = config.buildSessionFactory();
Session sess = sessFact.openSession();
Transaction trans = sess.beginTransaction();
Person p = new Person();
p.setPersonName("Suhail");
#ElementCollection//To inform hibernate to save this in a seperate table
Set<String> set = new HashSet<String>();
set.add("Address-1");
set.add("Address-2");
set.add("Address-3");
p.setAddressSet(set);
sess.save(p);
trans.commit();
}
}
Better to use Annotations so that we get rid of writing .hbm.xml mapping File
Related
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'm having a big problem trying to make this little program work
Here are my objects:
Class Country
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Country implements Serializable {
private static final long serialVersionUID = 4947071545454L;
private String countryID;
private String countryName;
private Set<City> cities = new HashSet<City>();
public Country() {
}
public Country(String countryID, String countryName, Set<City> cities) {
this.countryID = countryID;
this.countryName = countryName;
this.cities = cities;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getCountryID() {
return countryID;
}
public void setCountryID(String countryID) {
this.countryID = countryID;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public Set<City> getCities() {
return cities;
}
public void setCities(Set<City> cities) {
this.cities = cities;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Country country = (Country) o;
return countryID != null ? countryID.equals(country.countryID) : country.countryID == null;
}
#Override
public int hashCode() {
return countryID != null ? countryID.hashCode() : 0;
}
public boolean addCity(City c){
return cities.add(c);
}
public boolean removeCity(City c){
return cities.remove(c);
}
}
Class City
import java.io.Serializable;
public class City implements Serializable{
private static final long serialVersionUID = 49470713545454L;
private String cityName;
private Country id;
public City(String cityName, Country id) {
this.cityName = cityName;
this.id = id;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public Country getId() {
return id;
}
public void setId(Country id) {
this.id = id;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
City city = (City) o;
if (cityName != null ? !cityName.equals(city.cityName) : city.cityName != null) return false;
return id != null ? id.equals(city.id) : city.id == null;
}
#Override
public int hashCode() {
int result = cityName != null ? cityName.hashCode() : 0;
result = 31 * result + (id != null ? id.hashCode() : 0);
return result;
}
}
An here are my xml archives:
country.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="com.samuel.hibernate.Country" table="country" catalog="training2">
<id name="country" type="string" column="countryID">
<generator class="assign"/>
</id>
<property name="countryName" type="string">
<column name="countryName" length="40" not-null="true" unique="true" />
</property>
<set name="city" inverse="true" cascade="all">
<key column="countryID" not-null="true" />
<one-to-many class="com.samuel.hibernate.City"/>
</set>
</class>
</hibernate-mapping>
city.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="com.samuel.hibernate.City" table="city" catalog="training2">
<composite-id name="id">
<key-many-to-one name="countryID" class="com.samuel.hibernate.Country"
column="countryID" />
<key-property name="cityName" column="cityName" type="string"/>
</composite-id>
</class>
</hibernate-mapping>
And here's my main class:
Main class
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import java.util.HashSet;
import java.util.Set;
public class Main {
public static void main(String[] args) {
System.out.println("..");
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");
// aquí es donde peta si falla conexión con Postgres
//creating seession factory object
System.out.println("Antes de crear sesion");
SessionFactory factory=cfg.buildSessionFactory();
System.out.println("Despues de crear sesion");
//creating session object
Session session=factory.openSession();
//creating transaction object
Transaction t=session.beginTransaction();
Set<City> citiesSpain = new HashSet<>();
Country spain = new Country("es","Spain",citiesSpain);
citiesSpain.add(new City("Barcelona",spain));
citiesSpain.add(new City("Madrid",spain));
session.persist(spain);
t.commit();
session.close();
factory.close();
System.out.println("END");
}
}
When I execute this code I get this error message:
Exception in thread "main" org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.component.PojoComponentTuplizer]
at org.hibernate.tuple.component.ComponentTuplizerFactory.constructTuplizer(ComponentTuplizerFactory.java:98)
at org.hibernate.tuple.component.ComponentTuplizerFactory.constructDefaultTuplizer(ComponentTuplizerFactory.java:119)
at org.hibernate.tuple.component.ComponentMetamodel.<init>(ComponentMetamodel.java:68)
at org.hibernate.mapping.Component.getType(Component.java:169)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:422)
at org.hibernate.mapping.RootClass.validate(RootClass.java:266)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:329)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:451)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
at com.samuel.hibernate.Main.main(Main.java:22)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.tuple.component.ComponentTuplizerFactory.constructTuplizer(ComponentTuplizerFactory.java:95)
... 10 more
Caused by: org.hibernate.PropertyNotFoundException: Could not locate getter method for property [com.samuel.hibernate.Country#cityName]
at org.hibernate.internal.util.ReflectHelper.findGetterMethod(ReflectHelper.java:418)
at org.hibernate.property.access.internal.PropertyAccessBasicImpl.<init>(PropertyAccessBasicImpl.java:41)
at org.hibernate.property.access.internal.PropertyAccessStrategyBasicImpl.buildPropertyAccess(PropertyAccessStrategyBasicImpl.java:27)
at org.hibernate.mapping.Property.getGetter(Property.java:308)
at org.hibernate.tuple.component.PojoComponentTuplizer.buildGetter(PojoComponentTuplizer.java:138)
at org.hibernate.tuple.component.AbstractComponentTuplizer.<init>(AbstractComponentTuplizer.java:47)
at org.hibernate.tuple.component.PojoComponentTuplizer.<init>(PojoComponentTuplizer.java:41)
... 15 more
I've tried looking online but I don't seem to find the solution. In my example, one country can have many cities, but one city can only have on country.
This error means that one or more setters/getters is missing. Make sure you define matching getters/setters for all your properties. And make sure that your properties annotated correctly.
I think that problem is that your cities set name is different in a class and in hbm.xml file. In your entity class you defined set as Set<City> cities and in your XML file you defined this property as name="city". So hibernate is searching setters and getters for city named property.
Make sure that variable and property name coincides. And add empty constructor in City.class.
I am trying to use Hibernate but when I execute a query I receive a list of my entity where all the attributes are NULL. The thing is that when i use the jdbc directly I am able to retrieve the values from my Db.
I read similar articles about NULL values but couldn't figure out what s wrong in my case.
Below you see:
1) My entity: Eshop
public class Eshop implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public Eshop() {}
public Eshop(int eshopId, String code, String name, String lastModified) {
this.eshopId = eshopId;
this.code = code;
this.name = name;
this.lastModified = lastModified;
}
public int eshopId;
public String code;
public String name;
public String lastModified;
public int getEshopId() {
return eshopId;
}
public void setEshopId(int eshopId) {
eshopId = eshopId;
}
public String getCode() {
return code;
}
public void setCode(String code) {
code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
name = name;
}
public String getLastModified() {
return lastModified;
}
public void setLastModified(String lastModified) {
lastModified = lastModified;
}
2) The Hibernate Mapping
<hibernate-mapping>
<class name="dataModel.Eshop" table="Eshop">
<meta attribute="class-description">
This class contains the Eshop details.
</meta>
<id name="eshopId" type="int" column="EshopId">
<generator class="native"/>
</id>
<property name="code" column="Code" type="string"/>
<property name="name" column="Name" type="string"/>
<property name="lastModified" column="LastModified" type="string"/>
</class>
</hibernate-mapping>
And this is how I run the query:
Configuration config = new Configuration().configure();
SessionFactory sessionFactory = config.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Query hibernateQuery = session.createQuery("from Eshop");
List<Eshop> Eshops = hibernateQuery.list();
So when I run a query i receive the exact number of Eshops which are in my Db but all their attributes values are null!!
An ideas?? Thank you
All your setters are wrong:
public void setEshopId(int eshopId) {
eshopId = eshopId;
}
This is a noop. It should be
public void setEshopId(int eshopId) {
this.eshopId = eshopId;
}
Try to add hibernate.cfg.xml like this:
Configuration config = new Configuration().configure("hibernate.cfg.xml");
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
my classes seem to be mapped correctly (if I try persist an object it creates the table in the DB (if it's missing)) and I can query succesfully, but I can't get a newly created instance to be persisted to the DB.
I have show SQL queries in console, and it's not generating the insert query, but it's trying to select(max) id afterwards
Could someone please help me figure out why?
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
User myUser = new User();
myUser.setUserId("Acccc");
myUser.setPassword("abc");
session.save(myUser);
and class:
#Entity
#Table(name = "users")
#SuppressWarnings("serial")
public class User implements Serializable
{
//Properties
#Id
#Column
private int id;
#Column
private String userId;
#Column
private String password;
//Getters
public int getId() { return id; }
public String getUserId() { return userId; }
public String getPassword() { return password; }
//Setters
public void setId(int id) { this.id = id; }
public void setUserId(String userId) { this.userId = userId; }
public void setPassword(String password) { this.password = password; }
}
and config:
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="nz.co.genesis.healthsafety.stripes.model.User" table="users">
<id name="id" type="int" column="id" >
</id>
<property name="userId" type="java.lang.String" column="userId" not-null="false" length="45" />
<property name="password" type="java.lang.String" column="password" not-null="false" length="45" />
</class>
</hibernate-mapping>
And DB:
id : PK NN AI
userId varchar45, default NULL
password varchar45, default: null
This is my code for test hibernate model
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("hibernate.dialect", "org.hibernate.dialect.SQLServerDialect");
props.setProperty("hibernate.connection.driver_class", "com.microsoft.jdbc.sqlserver.SQLServerDriver");
props.setProperty("hibernate.connection.url", "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=databaseName");
props.setProperty("hibernate.connection.username", "username");
props.setProperty("hibernate.connection.password", "password");
props.setProperty("hibernate.show_sql", "true");
props.setProperty("hibernate.transaction.flush_before_completion", "true");
props.setProperty("hibernate.connection.release_mode", "auto");
props.setProperty("hibernate.transaction.auto_close_session", "true");
Configuration cfg = new Configuration();
cfg.setProperties(props);
// add dependency table class
cfg.addClass(ComputerModel.class);
cfg.addClass(CpuModel.class);
cfg.addClass(CdRomModel.class);
cfg.addClass(BrandModel.class);
SessionFactory sessions = cfg.buildSessionFactory();
Session ss = sessions.openSession();
List<ComputerModel> list = (ss.createQuery("from ComputerModel ")).list();
System.out.println("Found : " + list.size() + " items.");
System.out.println("======================================");
for (int i = 0; i < list.size(); i++) {
ComputerModel result = (ComputerModel) list.get(i);
System.out.println("computerSerialNo: " + result.getComputerSerialNo() +
", " + result.getCpuModel());
}
ss.close();
sessions.close();
}
I don't think you configuration of the Transaction Hibernate