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();
Related
I have two tables - Student and Address. They have one to many relationship. Student entity is having collection of address entity. When i updating collection of address in student. Its not updating the data and giving this error. When i was updating the parent entity with child collection, its taking next to be incremented key which is not in the database. -
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:124)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:189)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:59)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3079)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3521)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:88)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:395)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:387)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:303)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:349)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1195)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:404)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at com.HibernateExample.test.HibernateTest.main(HibernateTest.java:51)
Caused by: org.postgresql.util.PSQLException: ERROR: insert or update on table "address" violates foreign key constraint "student_fk"
Detail: Key (id)=(5) is not present in table "student".
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2476)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2189)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:300)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:428)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:354)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:169)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:136)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:186)
... 14 more
Student.java
public class Student {
public int id;
public String firstName;
public String lastName;
public int age;
public Set<Address> address = new HashSet<>(0);
public Set<Address> getAddress() {
return address;
}
public void setAddress(Set<Address> address) {
this.address = address;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Address.java
public class Address {
public int id;
public String streetName;
public String cityName;
public String stateName;
public String plotNo;
public Student student;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getStateName() {
return stateName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public String getPlotNo() {
return plotNo;
}
public void setPlotNo(String plotNo) {
this.plotNo = plotNo;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
}
HibernateTest.java
public class HibernateTest {
public static void main(String[] args) {
Configuration configuration = new Configuration();
configuration.configure("hibernate-cfg.xml");
#SuppressWarnings("deprecation")
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
session.setFlushMode(FlushMode.COMMIT);
System.out.println(session.getFlushMode().name());
Transaction transaction = session.beginTransaction();
Student student = (Student) session.get(Student.class, 3);
Address address = new Address();
address.setStateName("Kerala");
address.setCityName("Old Delhi");
address.setStreetName("Uttaam Nagar");
address.setPlotNo("158A");
address.setStudent(student);
student.getAddress().add(address);
session.update(student);
transaction.commit();
session.close();
sessionFactory.close();
}
}
address.hbm.xml
<hibernate-mapping>
<class name="com.HibernateExample.entity.Address" table="address">
<meta attribute="class-description">
This class contains the address detail.
</meta>
<id name="id" type="int" column="id">
<generator class="increment" />
</id>
<property name="streetName" column="street_name" type="string"/>
<property name="cityName" column="city_name" type="string"/>
<property name="stateName" column="state_name" type="string"/>
<property name="plotNo" column="plot_no" type="string"/>
<many-to-one name="student" class="com.HibernateExample.entity.Student" >
<column name="student_id" not-null="true"></column>
</many-to-one>
</class>
</hibernate-mapping>
student.hbm.xml
<hibernate-mapping>
<class name="com.HibernateExample.entity.Student" table="student">
<meta attribute="class-description">
This class contains the student detail.
</meta>
<id name="id" type="int" column="id">
<generator class="increment" />
</id>
<property name="firstName" column="first_name" type="string" length="40" />
<property name="lastName" column="last_name" type="string" length="40" />
<property name="age" column="age" type="int"/>
<set name="address" cascade="all">
<key column="student_id"/>
<one-to-many class="com.HibernateExample.entity.Address"/>
</set>
</class>
</hibernate-mapping>
From the Session javadoc, Session.update() is specified to work with a detached entity instance. "If there is a persistent instance with the same identifier, an exception is thrown." Exactly which exception is not specified, and cascading might send it down a complex code path, which could result in this error.
The Student object you modify is not detached, but rather persistent, because you got it by loading from the Session and have not closed the Session or done anything else that would detach it. This means that all modifications to it are saved to the database automatically, with no need for any manual call on Session. This is specified in the class javadoc for Session, with the sentence "Changes to persistent instances are detected at flush time and also result in an SQL UPDATE."
Simply delete the line session.update(student);, and I think your code will start working, including saving the new address through the cascaded relationship when you commit the transaction.
It's been a while since I've worked with cascades so I'm not entirely certain, but you might also need to set cascade on the other side of the relationship.
The "student_id" is not associated with any of your primary keys. If "student_id" exists in both Student and Address tables then change this line in your student mapping file from "id" to "student_id":
<id name="id" type="int" column="student_id">
Double check your database table with a database table viewer/browser.
It seems you try to insert an ID that already exists in the database (5)
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" ?
What is the equivalent way of defining dynamic component in hibernate by annotations?
public abstract class CustomizableEntity {
private Map customProperties;
public Map getCustomProperties() {
if (customProperties == null)
customProperties = new HashMap();
return customProperties;
}
public void setCustomProperties(Map customProperties) {
this.customProperties = customProperties;
}
public Object getValueOfCustomField(String name) {
return getCustomProperties().get(name);
}
public void setValueOfCustomField(String name, Object value) {
getCustomProperties().put(name, value);
}
}
my entity:
public class Contact extends CustomizableEntity {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
hibernate xml:
<hibernate-mapping auto-import="true" default-access="property" default-cascade="none" default-lazy="true">
<class abstract="false" name="com.enterra.customfieldsdemo.domain.Contact" table="tbl_contact">
<id column="fld_id" name="id">
<generator class="native"/>
</id>
<property name="name" column="fld_name" type="string"/>
<dynamic-component insert="true" name="customProperties" optimistic-lock="true" unique="false" update="true">
</dynamic-component>
</class>
</hibernate-mapping>
I want to use a dynamic-component by HashMap to create entities at runtime.
What is the equivalent way of defining dynamic component in hibernate by annotations?
http://www.infoq.com/articles/hibernate-custom-fields
this My Login.hbm.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Login1" table="Login1">
<id name="id" column="LID" type="integer">
<generator class="increment"></generator>
</id>
<property name="email" column="EMAIL" type="string"></property>
<property name="password" column="PASS" type="string"></property>
</class>
</hibernate-mapping>
Could not get constructor for
org.hibernate.persister.entity.SingleTableEntityPersister
This is my class file:
public class Login1 implements Serializable {
private int id;
private String email;
private String password;
private String name;
private String amount;
private String date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
My Login1 has more property but i want add only email and password
please check your constructor,set and get methods of your login class.Check if there are some mis spelling or if they are missing
refer https://forum.hibernate.org/viewtopic.php?p=2453286
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>