javamysqlhibernategetter-settersessionfactory

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 i.e. address and salary) it assigns NULL to them. 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. Is there any other solutions???

Edit :

The below code are written in "Java Project" and not "Maven Project". The files "MainExecute.java" and "employee.java" are in package "Lab3" The files "employee.hbm.xml" and "hibernate.cfg.xml" are in the "src" Folder of the same Project.

Here are the codes

MainExecute.java

package Lab3;

import java.util.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class MainExecute {

    SessionFactory sc = new Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

    
    public void insert(int empid,String name,int salary,String address) {
        Session session = sc.openSession();
        Transaction t = session.beginTransaction();
        employee e1=new employee();
        e1.setEmpid(empid);
        e1.setName(name);
        e1.setSalary(salary);
        e1.setAddress(address);
        session.save(e1);
        t.commit();
        System.out.print("Entered Succesfully");
        }

    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;
        //Saved the attributes that exist so that i can bypass the NULL assignment
        Salary=e1.getSalary();
        Address=e1.getAddress().toString();
        //Detached the object from the session else it creates error, 
        //since hibernate cannot push parallel transaction on same reference objects
        session.evict(e1);
        employee e2=new employee();
        //Setting the attributes that you want to update and rest with already backed up values from attribute
        e2.setEmpid(empid);
        e2.setName(name);
        e2.setAddress(Address);
        e2.setSalary(Salary);;
        session.saveOrUpdate(e2);
        t.commit();
    }
    
    public void delete(int empid) {
        Session session = sc.openSession();
        Transaction t = session.beginTransaction();
        employee e1=new employee();
        e1.setEmpid(empid);
        session.delete(e1);
        t.commit();
    }
    
    public void display() {
        Session session = sc.openSession();
        Transaction t = session.beginTransaction();
        Query q = session.createQuery("from employee");
        List<?> l = q.getResultList();
        Iterator<?> it = l.iterator();
        if(!it.hasNext()) {
            System.out.println("\n\nNo Employees!!!\n");

        }
        while (it.hasNext()) {
            employee e1 = (employee) it.next();
            System.out.println("\nEmp ID :"+e1.getEmpid()+
                    "\t\tName :"+e1.getName()+
                    "\nSalary :"+e1.getSalary()+
                    "\t\tAddress :"+e1.getAddress());
        }
        t.commit();
        }
    
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MainExecute m1=new MainExecute();
        Scanner sc=new Scanner(System.in);
        int empid,salary,ch=0;
        String name,address;
        while(true) {
        System.out.println("\n\n1.Insert\t2.Update\n3.Delete\t4.Display\nPress 0 to exit\n");
        ch=sc.nextInt();        
            if(ch==1) {
                System.out.println("Emp ID :");
                empid=sc.nextInt();
                System.out.println("Name :");
                name=sc.next();
                System.out.println("Salary :");
                salary=sc.nextInt();
                System.out.println("Address :");
                address=sc.next();
                m1.insert(empid, name, salary, address);
            }else
            if(ch==2) {
                System.out.println("Emp ID :");
                empid=sc.nextInt();
                System.out.println("Name :");
                name=sc.next();
                m1.update(empid, name);
            }else
            if(ch==3) {
                System.out.println("Emp ID :");
                empid=sc.nextInt();
                m1.delete(empid);
            }else
            if(ch==4) {
                m1.display();
            }else
            if(ch==0) {
                break;
            }
        }
    }
}

employee.java

package Lab3;
//Persistence Class
import javax.persistence.*;
@Entity
@Table(name="employee")

public class employee {
    @Id
    int empid;
    int salary;
    String name,address;
    
public String getName() {
    return name;
    }
public void setName(String name) {
    this.name = name;
    }
public int getSalary() {
    return salary;
    }
public void setSalary(int salary) {
    this.salary = salary;
    }
public int getEmpid() {
    return empid;
    }
public void setEmpid(int empid) {
    this.empid = empid;
    }
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}
}

employee.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<hibernate-mapping>
<class name="Lab3.employee" table="employee">
<id name="empid" type="int" column="empid"></id>
<property name="name" type="string" column="name" />
<property name="salary" type="int" column="salary" />
<property name="address" type="string" column="address" />
</class>
</hibernate-mapping>

and hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.password">1506</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/java</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <mapping class="Lab3.employee"/>
        <mapping resource="employee.hbm.xml"/>
    </session-factory>
</hibernate-configuration>


Solution

  • If you can use hibernate, why don't you can use JPA?

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