hibernate的setParameter函数不起作用

时间:2013-06-04 07:07:50

标签: hibernate java-ee

我正在尝试更新数据库上的记录,我使用以下代码来执行此操作,

System.out.print("Update");
Session session1 = HibernateUtil.getSessionFactory().openSession();
Query q = session1.createQuery("FROM Developer WHERE id = :id");
q.setParameter("id", 1);
Developer developer = (Developer)q.list().get(0);
developer.setContact("Jack");
session1.update(developer);

一旦我运行该项目,它就会在控制台上显示以下内容,而不会更进一步。

INFO: Update
INFO: Hibernate: select developer0_.id as id0_, developer0_.contact as contact0_,   
   developer0_.phone_1 as phone3_0_
   from developer developer0_ where developer0_.id=?

Developer.java

package net.viralpatel.contact.model;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
/**
 *
 * @author Jack
 */
@Entity
@Table(name="developer")
public class Developer implements Serializable {

    private static final long serialVersionUID = -8767337896773261247L;

    private int id;
    private String contact;
    private int phone_1;

    @Id
    @GeneratedValue
    @Column(name="id")
    public int getID() {
        return id;
    }

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

    @Column(name="contact")
    public String getContact() {
        return contact;
    }

    public void setContact(String Contact) {
        this.contact = Contact;
    }

    @Column(name="phone_1")
    public int getPhone_1() {
        return phone_1;
    }

    public void setPhone_1(int Phone_1) {
        this.phone_1 = Phone_1;
    }


}

我可以使用以下代码将行插入到数据库

的同一个表中
Session session1 = HibernateUtil.getSessionFactory().openSession();
session1.beginTransaction();
session1.save(developer);
session1.getTransaction().commit();

1 个答案:

答案 0 :(得分:1)

为什么不在update方法中打开事务?你应该总是使用交易。

Session session1 = HibernateUtil.getSessionFactory().openSession();
        session1.beginTransaction();
 Query q = session1.createQuery("FROM Developer WHERE id = :id");
    q.setParameter("id", 1);
    Developer developer = (Developer)q.list().get(0);
    developer.setContact("Jack");
    session1.update(developer);
 session1.getTransaction().commit();

为什么你不使用session.get来获取带有id的对象而不是使用查询? 你可以这样做。

Session session1 = HibernateUtil.getSessionFactory().openSession();
            session1.beginTransaction();
        Developer developer = (Developer)session1.get(Developer.class,1);
        developer.setContact("Jack");
        session1.update(developer);
     session1.getTransaction().commit();