简体   繁体   中英

Hibernate refresh in many-to-one relation

I have this 2 domain Model :

Employee

public class Employee {

    private Long    id; 
    private String  name;
    private String  family;
    private Company company;

    //getter & setter

}

and Company :

public class Company {

private Long            id; 
private String          name; 
private Set<Employee>   employees;

//getter & setter 

}

and Employee has a many-to-one relation with Company , and from Company side there is one-to-many relation .

i save a Company Object in transaction and after save the Employee with that company :

@Transactional
puplic Long Save (){
        Company cmp=new Company(); 
        cmp.setName("Oracle");
        session.save(cmp);
        Employee employee=new Employee();
        employee.setName("james");
        employee.setFamily("dep");
        employee.setCompany(cmp);
        cmp.getEmployees();//will raise NullPointerException
        cmp=session.get(cmp.getId());//because of first level cache it doesnt load it 
    }

after save employee if i want to get the collection of employee from company it it will raise the null pointer exception and if i want to load it because of first level cache hibernate will not touch the database and the set of employee is still null .

the first solution is that i can refresh the Company object after save the employee , but i think hibernate must have solution except of it .

You should never use null collections, so you should change your mapping to this:

private Set<Employee>   employees = new HashSet<>();

This way, you don't even need a setter, since a getter is sufficient. Also, make sure you synchronize both sides of the bidirectional association:

public void addEmployee(Employee employee) {
     employees.add(employee);
     employee.setCompany(this);
}

public void removeEmployee(Employee employee) {
     employees.remove(employee);
     employee.setCompany(null);
}

You also need to implement equals and hashCode properly in your child entity classes.

Look into my code ,

After commit() the transaction only u can get persistant object,

public class Employee {

    private Long    id; 
    private String  name;
    private String  family;

    @ManyToOne
    @JoinColumn(name = "company_id_fk")
    private Company company;

    //getter & setter

}


public class Company {

    private Long            id; 
    private String          name; 

    @OneToMany(mappedBy="company")
    List<Employee> listOfEmployees = new ArrayList<Employee>();

    //getter & setter 
}


puplic Long Save (){

    Session session = sessionFactory.openSession();
    Transaction transaction = session.beginTransaction();
    try{
        Company cmp=new Company(); 
        cmp.setName("Oracle");
        session.save(cmp);

        Employee employee=new Employee();
        employee.setName("james");
        employee.setFamily("dep");
        employee.setCompany(cmp);
        session.save(employee);

        transaction.commit();

        List<Employee> listOfEmployees = cmp.getListOfEmployees();
        if(listOfEmployees !=null && !listOfEmployees .isEmpty()){
            for(Employee employ:listOfEmployees){
              //You can wt you want
            }
        }


    }catch(Exception e){
        transaction.rollback();
    }finally{
        session.close();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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