休眠将对象值复制到具有新生成ID的新对象中 [英] hibernate copy object values into new object with new generated ID

查看:71
本文介绍了休眠将对象值复制到具有新生成ID的新对象中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一个带有少量嵌套表的单列pk的关系数据库。我需要添加简单的归档到我的项目中。归档只发生在应用程序到达特定状态时,所以我希望做的是将现有的hibernate对象复制到新实例中,新实例将使用新ID保存,同时保持现有对象不变。我似乎无法弄清楚如何将现有对象复制到新实例中,而无需手动设置每个新实例字段。有人知道这样做的一个简单方法吗?

I'm using a relational db using a single column pk with a few nested tables. I need to add simple archiving to my project. The archiving only happens when the application reaches a particular state, so what I was hoping to do was copy my existing hibernate object into a new instance where the new instance would be saved with a new ID while leaving the existing object intact. I can't seem to figure out how to copy the existing object into a new instance without manually having to set every single new instance field. Does anybody know of a simple way of doing this?

推荐答案

我也在使用Hibernate,并且我得到了与您相同的要求。我遵循的是实现 Cloneable

I am also working with Hibernate and I got the same requirement you got. What I followed was to implement Cloneable. Below is a code example of how to do it.

class Person implements Cloneable {

        private String firstName;
        private String lastName;

        public Object clone() {

            Person obj = new Person();
            obj.setFirstName(this.firstName);
            obj.setLastName(this.lastName);

            return obj;
        }

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    }

或者你可以去基于反射的解决方案,但是我不会推荐。请查看网站了解更多详情。

Or you could go to a reflection based solution but I won't recommend that. Check this website for more details.

这篇关于休眠将对象值复制到具有新生成ID的新对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆