简体   繁体   English

如何使用 Hibernate 仅更新数据库的一个属性...因为它由于 getter 和 setter 分配了 NULL 值?

[英]How to update only one attribute of Database using Hibernate... Since it assigns NULL values due to getters and setters?

I am trying to update a row by using its primary key, the issue is that Hibernate updates entire row and since I have not passed values for any other attributes (For Ex: Attributes are empid, name salary and address. I will pass empid=1 and name to be updated. But it will set NULL to other 2 values ie address and salary) it assigns NULL to them.我正在尝试使用其主键更新一行,问题是 Hibernate 更新了整行,因为我没有传递任何其他属性的值(例如:属性是 empid,名称是薪水和地址。我将通过 empid= 1 和要更新的姓名。但它会将 NULL 设置为其他 2 个值,即地址和薪水),并将 NULL 分配给它们。 I want to Update only selective attributes;我只想更新选择性属性;

I tried using saveOrUpdate but that too is either entering new or updating same row with NULL values.我尝试使用 saveOrUpdate 但这也是输入新的或使用 NULL 值更新同一行。 Is there any other solutions???还有其他解决办法吗???

I figured the following works.我想出了以下作品。 The code below is the update method in my execution file which is called.下面的代码是我调用的执行文件中的更新方法。

public void update(int empid,String name) {
    Session session = sc.openSession();
    Transaction t = session.beginTransaction();
    Query q = session.createQuery("from employee");
    List<?> l = q.getResultList();
    Iterator<?> it = l.iterator();
    employee e1 = (employee) it.next();
    String Address;
    int Salary;
    Salary=e1.getSalary();
    Address=e1.getAddress().toString();
    session.evict(e1);
    employee e2=new employee();
    e2.setEmpid(empid);
    e2.setName(name);
    e2.setAddress(Address);
    e2.setSalary(Salary);;
    session.saveOrUpdate(e2);
    t.commit();
    
}

If you can use hibernate, why don't you can use JPA?如果可以使用hibernate,为什么不能使用JPA呢?

var entity = repo.getById( id );
entity.setValue( value );
repo.save(); // or repo.saveAndFlush();

Try use the native sql to update尝试使用原生sql更新

    Session session = sessionFactory.openSession();
    Transaction t = session.beginTransaction();
    Query query = session.createQuery("update employee e set e.name = 'newvalue' where e = 1");
    query.executeUpdate();
    t.commit();

I agree with Jan Tibar said that Jpa is more convenient than hibernate我同意Jan Tibar所说的 Jpa 比 hibernate 更方便

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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