如果数据存在则休眠保存正确的外键

时间:2018-02-01 13:20:50

标签: java mysql hibernate

我使用表Address中的外键创建了表Employee。当我保存新员工时,我想检查表格地址中是否已存在该地址,如果存在,则不要在地址中创建新行但找到正确的并将其保存在员工中。

我用SQL做了这个程序,但是使用hibernate更容易吗?使用此代码,我总是有新的行。我试图提取查询但我不知道如何使用此地址ID分配给Employee,而不是在地址中插入新行。在图片上是表,所以我很想知道我想要什么。 table looklink to project

Employee employee = new Employee();
Address address = new Address();
City city = new City();


 /*   Query query = session.createQuery("select  a.address_id  from Address  
a where a.street = :addName").setParameter("addName" , 
JFClasss.insStreet.getText());
List list = query.list();
if(!list.isEmpty()){

    addid = (int) list.get(0);
    address.setAddressId(addid);
   // save = 1;

} */

   address.setStreet(jf.insStreet.getText());
   city.setCityName(jf.insStreet.getText());
   employee.setName(jf.insName.getText());
   employee.setSurname(jf.insSurname.getText());
   employee.setAge(age);
   employee.setAddress(address);
   employee.setCity(city);


 session.saveOrUpdate(city);
 session.save(address);
 session.save(employee);     

1 个答案:

答案 0 :(得分:0)

解决了,我可以使用saveOrUpdate获取整个对象并再次保存。

Employee employee = new Employee();
Address address;
City city = new City();


Query query = session.createQuery("select  a.address_id  from Address  a 
where a.street = :addName").setParameter("addName" , 
JFClasss.insStreet.getText());
List list = query.list();
if(!list.isEmpty()){

    addid = (int) list.get(0);
    address = (Address) session.get(Address.class, addid);
   // address.setAddressId(addid);
   // save = 1;

} 
else{
      address = new Address();
      address.setStreet(jf.insStreet.getText());
  }
 .
 .
 .
  session.saveOrUpdate(address);