配置文件
- XML code
<class name="org.model.Customer" table="customers" lazy="false" dynamic-update="true" dynamic-insert="true"> <id name="id" type="java.lang.String" column="ID" > <generator class="uuid.hex" /> </id> <property name="name" type="java.lang.String" column="NAME" length="15" /> <property name="sex" type="java.lang.String" column="SEX" length="1" /> <property name="description" type="java.lang.String" column="DESCRIPTION" length="65535" /> <!-- Associations --> <!-- bi-directional one-to-many association to Order --> <set name="orders" lazy="true" inverse="true" cascade="all" > <key> <column name="CUSTOMER_ID" /> </key> <one-to-many class="org.model.Order" /> </set></class>
java代码:
- Java code
package test;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;import org.model.Customer;public class Test { private static SessionFactory sessionFactory; static{ sessionFactory = new Configuration().configure().buildSessionFactory(); } public void createNewCustomer(Customer c){ Session sess = sessionFactory.openSession(); Transaction tx = sess.beginTransaction(); sess.save(c); tx.commit(); } public void updateCustomer(Customer c ){ Session sess = sessionFactory.openSession(); Transaction tx = sess.beginTransaction(); sess.update(c); tx.commit(); } public static void main(String[] args) { Test t = new Test(); Customer c = new Customer(); c.setId("8a8482d51d18ec17011d18ec1a750001"); c.setDescription("sdfsdfdsfsdf"); t.updateCustomer(c); }}
运行结果:
Hibernate: update customers set NAME=?, SEX=?, DESCRIPTION=? where ID=?
应该是update customers set DESCRIPTION=? where ID=? 这样才对吧
------解决方案--------------------
输出结果没错,因为你new了一个Customer c ,你并没有从数据库中load或者get这个实体,所以缓存上没有这个实体,session就根据id更新c中所有的属性