Sergei
Sergei

Reputation: 51

Hibernate: update instead insert

I have entity:

@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
}

I get user from BD and do xml:

<user>

        <name>123</name>

        <id>35</id>

</user>

Next I get new User from this xml and try to save in BD.

session.save(user);

If list lessonList of user is empty Hibernate inserts NEW user in BD. If list is not empty Hibernate uses update. Why?

I use 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
        }

create XML with JAXB

@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;
}

controller:

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

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

        }
    }

Upvotes: 1

Views: 3609

Answers (1)

Felice Pollano
Felice Pollano

Reputation: 33272

You are specifying that the object id is assigned automatically. if you are providing an ID yourself, Hibernate guess you already have that entity saved ( so you know the id ) and for that reason is issuing an update.

Upvotes: 2

Related Questions