休眠中的保存方法不立即插入

Posted

技术标签:

【中文标题】休眠中的保存方法不立即插入【英文标题】:save method in hibernate not inserting immediately 【发布时间】:2015-01-02 06:50:17 【问题描述】:

根据我阅读的文件here 它说:

Hibernate save 方法立即返回生成的 id,这是可能的,因为一旦调用 save 方法,主对象就会被保存。

但在下面的示例中,我触发了 save 方法,然后让线程休眠 1 分钟。 在这个时间空间内,当我检查数据库时,person_o 表中没有显示任何数据。为什么保存后不立即显示年龄和名称值。虽然它会在睡眠结束后执行提交后出现。

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>

我的输出是:

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 (?, ?, ?, ?, ?, ?)

请纠正我的知识。

谢谢

贾延德拉·巴特

【问题讨论】:

【参考方案1】:

session.save(Object), sesson.saveOrUpdate(Object) 等方法只将任何瞬态对象转换为持久对象, 表示对象与当前休眠会话相关联(实际上对象与会话功能队列相关联,例如插入队列, 根据相应操作更新队列等)并获取休眠生成(由生成器类提供)id 如果它是一个新对象。它绝不意味着该对象将立即映射到数据库上。 当当前休眠会话刷新或休眠事务提交时,只有实际查询运行以映射对象数据 进入数据库。

【讨论】:

以上是关于休眠中的保存方法不立即插入的主要内容,如果未能解决你的问题,请参考以下文章

SQLite 不立即插入记录

win7系统设置电脑不待机状态的操作方法

休眠保存或更新行为

如何强制 django 立即保存而不是在循环后进行批量更新

序列化程序中的django rest框架更新方法,实例不会立即保存

如何使用休眠插入加密数据