2016-11-14 129 views
0

我有實體:休眠:更新,而不是插入

@Entity 
@Table(name = "users") 
public class User { 
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private int id; 

    @Column(name = "name", nullable = false) 
    private String name; 

@OneToMany(fetch = FetchType.LAZY, mappedBy = "parentid", cascade=CascadeType.ALL) 
    private List<Lesson> lessonList = new ArrayList<>(); 
....setters/getters 
} 

我從BD獲得用戶做的xml:

<user> 

     <name>123</name> 

     <id>35</id> 

</user> 

接下來,我從這個XML獲得新用戶,並嘗試在BD保存。

session.save(user); 

如果用戶列表lessonList爲空Hibernate在BD中插入NEW用戶。如果列表不爲空Hibernate使用更新。爲什麼?

我使用JAXB

User.class 

    @Entity 
     @Table(name = "users") 
     public class User { 
      @Id 
      @GeneratedValue(strategy = GenerationType.AUTO) 
      private int id; 

      @Column(name = "name", nullable = false) 
      private String name; 

     @OneToMany(fetch = FetchType.LAZY, mappedBy = "parentid", cascade=CascadeType.ALL) 
      private List<Lesson> lessonList = new ArrayList<>(); 
     ....setters/getters 
     } 

與JAXB

創建XML
@Transactional 
    public User getUserFromXML(int id) { 
     StringWriter stringWriter = new StringWriter(); 
     User copyUser = null; 
     User user = UserDAO.getById(id); 
     try { 
      JAXBContext jaxbContext = JAXBContext.newInstance(User.class); 
      Marshaller marshaller = jaxbContext.createMarshaller(); 
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); 
      marshaller.marshal(user, stringWriter); 
      StringReader stringReader = new ringReader(stringWriter.toString()); 
      Unmarshaller unmarshaller = jaxbContext.createUnmarshaller(); 
      copyUser = (User) unmarshaller.unmarshal(stringReader); 
      } catch (JAXBException e) { 
      e.printStackTrace(); 
     } 
     return copyUser; 
} 

控制器:

@Transactional 
    void copyUser(HttpServletRequest request, HttpServletResponse response) { 

       User copyUser = getUserFromXML(idUser);// it get from Client 
       copyUser.setParentid(getLoginUser()); 
       userDAO.save(copyUser); 

     } 
    } 
+1

向我們展示您用來測試它的休眠日誌和實際代碼。 – Antoniossss

+0

@Antoniossss我添加了代碼 – Sergei

回答

2

你指定的對象ID自動分配。如果你自己提供了一個ID,Hibernate猜測你已經保存了該實體(所以你知道這個ID),並且因此發佈了一個更新。

+0

但是,如果列表爲空,那麼我可以製作多份副本。有什麼不同? – Sergei