简体   繁体   中英

save method in hibernate not inserting immediately

As per the document i read here it says :

Hibernate save method returns the generated id immediately, this is possible because primary object is saved as soon as save method is invoked.

But in my example below, i have fired the save method and then kept the thread on sleep for 1 minute. Within this timespace when i check the database the person_o table doesnt show any data in it. why isnt it showing the age and name value in it immediately after save. though it appears after the commit is executed once sleep is over .

addperson.java:

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;


public class addperson {

    public static void main(String as[])
    {

               //Activate Hibernate Software
    Configuration cfg=new Configuration();
    //make hibernate software locating and reading cfg file
    cfg=cfg.configure("/hibernate.cfg.xml");
    //create SessionFactory obj
    SessionFactory factory=cfg.buildSessionFactory();
    //create HB session obj
    Session session=factory.openSession();



            Transaction tx = session.beginTransaction();

            try {

                // Create a person
                person person = new person();
                person.setName("Luna");
                person.setAge(33);

                Integer key = (Integer) session.save(person);
                System.out.println("Primary Key : " + key);
                person.setId(key);
                System.out.println("---going for sleep---");
Thread.sleep(60000);
                // Create the address for the person
                personaddress address = new personaddress();
                address.setAddressLine1("Lunaris");
                address.setCity("Twinkle");
                address.setState("MA");
                address.setZipCode(10308);
                address.setPerson(person);

                person.setAddress(address);

                key = (Integer) session.save(address);
                System.out.println("Primary Key again : " + key);
                tx.commit();
            } catch (Exception e) {
                e.printStackTrace();
                tx.rollback();
            } finally {
                session.close();
            }
        }
    }

person.java

import java.io.Serializable;

public class person implements Serializable {

    private static final long serialVersionUID = -9127358545321739524L;

    private int id;
    private String name;
    private int age;
    private personaddress address;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public personaddress getAddress() {
        return address;
    }

    public void setAddress(personaddress address) {
        this.address = address;
    }
}

personaddress.java

import java.io.Serializable;

public class personaddress implements Serializable {

    private static final long serialVersionUID = -9127358545321739523L;

    private int id;
    private String addressLine1;
    private String city;
    private String state;
    private int zipCode;
    private person person;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getAddressLine1() {
        return addressLine1;
    }

    public void setAddressLine1(String addressLine1) {
        this.addressLine1 = addressLine1;
    }

    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 int getZipCode() {
        return zipCode;
    }

    public void setZipCode(int zipCode) {
        this.zipCode = zipCode;
    }

    public person getPerson() {
        return person;
    }

    public void setPerson(person person) {
        this.person = person;
    }
}

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.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="hibernate.connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
        <property name="hibernate.connection.username">system</property>
        <property name="hibernate.connection.password">oracle123</property>

        <property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
        <property name="hibernate.hbm2ddl.auto">create</property>
        <property name="show_sql">true</property>
        <mapping resource="person.hbm.xml"/>            <mapping resource="personaddress.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

person.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="person" table="persons_o">
        <id name="id" column="P_ID" type="integer">
            <generator class="increment" />
        </id>

        <property name="name" column="NAME" update="false"
            type="string" />

        <property name="age" column="AGE" type="integer" />

        <one-to-one name="address" cascade="all"></one-to-one>
    </class>
</hibernate-mapping>

personaddress.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="personaddress" table="address_o"
        dynamic-insert="true" dynamic-update="true"
        select-before-update="false">
        <id name="id" column="A_ID" type="integer">
            <generator class="increment" />
        </id>

        <property name="addressLine1" column="ADDRESS_LINE_1"
            type="string" />

        <property name="city" column="CITY" type="string" />

        <property name="state" column="STATE" type="string" />

        <property name="zipCode" column="ZIPCODE" type="integer" />

        <!-- In One-to-one we cannot specify the foreign key column 
             that has to be filled up
            <one-to-one name="person" class="PersonOTO_B" cascade="all"
            constrained="true"> </one-to-one>
        -->

        <many-to-one name="person" column="P_ID" unique="true"
            not-null="true" lazy="false" />
    </class>
</hibernate-mapping>

My output is :

log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Hibernate: select max(P_ID) from persons_o
Primary Key : 1
---going for sleep--- (i am checking my db at this point but no data found )
Hibernate: select max(A_ID) from address_o
Primary Key again : 1
Hibernate: insert into persons_o (NAME, AGE, P_ID) values (?, ?, ?)
Hibernate: insert into address_o (ADDRESS_LINE_1, CITY, STATE, ZIPCODE, P_ID, A_ID) values (?, ?, ?, ?, ?, ?)

Please correct my knowledge.

Thanks

Jayendra Bhatt

session.save(Object), sesson.saveOrUpdate(Object) and etc. method only converts any transient object into persistence object, means object associates with current hibernate session(actually object associates with session functional queues eg insertion queue, updation queue and etc. according to corresponding operation) and gets hibernate generated(provided by generator class) id
if it's a new object. it never means that object will be immediately mapped on database. When current hibernate session flushes or hibernate transaction commits then only actual query runs to map object data into the database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM