I have confusion on concept of cascading in hibernate.Why isn't it saving the car automatically,While it is expected to be done on cascading?
Code:
<?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>
<class name="hibernateoobdemo.pojos.Car" table="Car">
<id name="carno" column="carnum" type="integer">
<generator class="native"></generator>
</id>
<property name="carname" type="string" column="carname"></property>
<many-to-one name="person" class="hibernateoobdemo.pojos.Person" cascade="all" unique="true"></many-to-one>
</class>
</hibernate-mapping>
Code:
<?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>
<class name="hibernateoobdemo.pojos.Person" table="Person">
<id name="code" type="integer">
<generator class="native"></generator>
</id>
<property name="name" type="string" column="name"></property>
<one-to-one name="car" class="hibernateoobdemo.pojos.Car" property-ref="person"></one-to-one>
</class>
</hibernate-mapping>
Code:
package hibernateoobdemo;
import org.hibernate.*;
import org.hibernate.cfg.*;
import hibernateoobdemo.pojos.*;
public class Hibernateoobdemo
{
public static void main(String[] args)
{
SessionFactory sf=new Configuration().configure().buildSessionFactory();
Session session=sf.openSession();
Transaction t=session.beginTransaction();
t.begin();
Car car=new Car();
car.setCarname("AUDI");
Person person=new Person();
person.setName("Ravi");
car.setPerson(person);
person.setCar(car);
session.save(person);
t.commit();
session.close();
}
}
Code:
package hibernateoobdemo.pojos;
public class Car
{
private int carno;
private String carname;
private Person person;
public int getCarno() {
return carno;
}
public String getCarname() {
return carname;
}
public Person getPerson() {
return person;
}
public void setCarno(int carno) {
this.carno = carno;
}
public void setCarname(String carname) {
this.carname = carname;
}
public void setPerson(Person person) {
this.person = person;
}
}
Code:
package hibernateoobdemo.pojos;
public class Person
{
private int code;
private String name;
private Car car;
public int getCode() {
return code;
}
public String getName() {
return name;
}
public Car getCar() {
return car;
}
public void setCode(int code) {
this.code = code;
}
public void setName(String name) {
this.name = name;
}
public void setCar(Car car) {
this.car = car;
}
}