在Hibernate的映射文件的class tag使用dynamic-insert,dynamic-update,可以优化生成的SQL语句,提高SQL执行效率,最终可以提高系统性能。
如,有一个User类。
public class User {
/** Creates a new instance of User */
public User() {
}
private long id;
private int age;
private String firstname;
private String lastname;
private Set emailAddresses;
//省略getter 和setter方法
}
Hibernate映射文件(User.hbm.xml,省略了文件头声明)定义为:
<hibernate-mapping> <class name="model.User" table="Users" > <id name="id" column="ID"> <generator class="native"/> </id> <property name="age"/> <property name="firstname"/> <property name="lastname"/> <set name="emailAddresses" table="PERSON_EMAIL_ADDR"> <key column="PERSON_ID"/> <element type="string" column="EMAIL_ADDR"/> </set> </class> </hibernate-mapping>
我们写一个测试类进行测试UserTest。
public class UserTest extends TestCase {
public UserTest(String testName) {
super(testName);
}
private Session session;
private SessionFactory sessionFactory;
protected void setUp() throws Exception {
sessionFactory=HibernateUtil.getSessionFactory();
session=sessionFactory.openSession();
session.getTransaction().begin();
}
protected void tearDown() throws Exception {
session.getTransaction().commit();
session.close();
}
/**
* Test of getAge method, of class model.User.
*/
public void testSaveUser() {
System.out.println("================testSaveUser=================");
User user = new User();
user.setAge(29);
session.save(user);
assertNotNull("id is assigned !",user.getId());
}
public void testUpdateUser() {
System.out.println("================testUpdateUser=================");
User user = new User();
user.setAge(29);
session.save(user);
assertNotNull("id is assigned !",user.getId());
User _user=(User) session.get(User.class, user.getId());
_user.setFirstname("Array");
session.update(_user);
}
}
运行测试后,此时会生成完整的SQL语句(注意将hibernate属性show_sql设置成true)。
================testSaveUser=================
Hibernate: insert into Users (age, firstname, lastname) values (?, ?, ?)
================testUpdateUser=================
Hibernate: insert into Users (age, firstname, lastname) values (?, ?, ?)
Hibernate: update Users set age=?, firstname=?, lastname=? where ID=?
如果我们在<class ...>中加上 dynamic-insert="true" dynamic-update="true",变成如下。
<class name="model.User" table="Users" dynamic-insert="true" dynamic-update="true">
再次运行测试类,就会发现生成的SQL中涉及的字段只包含User类中修改的属性所对应的表字段。
================testSaveUser=================
Hibernate: insert into Users (age) values (?)
================testUpdateUser=================
Hibernate: insert into Users (age) values (?)
Hibernate: update Users set firstname=? where ID=?
如果一个表的结构很复杂,字段很多的情况下,使用dynamic-insert,dynamic-update能够性能上的少许提升。