Is it possible to detach Hibernate entity, so that changes to object are not automatically saved to database?

前端 未结 5 1235
野性不改
野性不改 2020-11-30 00:12

I have Hibernate entity that I have to convert to JSON, and I have to translate some values in entity, but when I translate values, these values are instantly saved to datab

5条回答
  •  盖世英雄少女心
    2020-11-30 00:49

    public static  E deepClone(E e) {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        ObjectOutputStream oo;
        try {
            oo = new ObjectOutputStream(bo);
            oo.writeObject(e);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
        ObjectInputStream oi;
        try {
            oi = new ObjectInputStream(bi);
            return (E) (oi.readObject());
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            return null;
        }
    }
    

    first: deepClone the session pojo
    second: alter fields
    then: do whatever you want to do

提交回复
热议问题