user5620472
user5620472

Reputation: 2882

How copy List<Entity> to new List without ID?

I have some Entity for example User

class User{
 private Long id;
 private String Name;
 private List<Role> roles;
}

When I get this User from DB I have user = UserDao.getUser(1);

And I have some List<Role> someList;

I need copy user.getRoles() to someList

But if I write user = user.getRoles() all Role objects in someList have ID not null;

I want to set someList to another User but if ID is not null, I can not use it.

I can make this

for (Role role: user.getRoles()) {
            role.setId(null);
            someList.add(role);
        }

But I think it is bad practice. Maybe you know best way?

Upvotes: 0

Views: 898

Answers (2)

kaba713
kaba713

Reputation: 494

Here is a example. I made up the Role Class myself since you did not provide any source code of it:

public class Role {
    private int id;
    private String someAttribute;
    private int otherAttribute;

    public Role(String someAttribute, int otherAttribute) {
        this.someAttribute = someAttribute;
        this.otherAttribute = otherAttribute;
    }

    // Other class methods omited for readability

    public Role clone() {
        return new Role(someAttribute, otherAttribute);
    }

}

Edit: And you could do your for loop like this:

for (Role role: user.getRoles()) {
    someList.add(role.clone());
}

Upvotes: 0

Augusto
Augusto

Reputation: 29997

Assuming you are inside a transaction and that don't want to reuse the Role objects across different users: With the way hibernate works, you'll need create new role objects, otherwise Hibernate will know that you assigned the same instance to another object, and will completely ignore that you have set the id to null.

Personally, I think would create a static method in Role class called clone that receives a list of roles and instantiates new ones (without an id).

The big, important question is: Do you really want to not re-use the role objects? And potentially have 2 roles with the same data, but just assigned to different users (that might go against 3rd normal form... but this depends on your requirements).

Upvotes: 1

Related Questions