在 OpenJPA 2.2 中,当我分离某个实体时,所有列表属性都是“只读(不可变)我无法更改它们,但我可以更改一些其他属性,例如字符串”。
这是任何实体中列表属性的正常行为吗?或者仅仅是openjpa的一个限制,规范所说的正常行为是什么?
实体
@Entity
public class User implements Serializable{
@Id
private int id;
private String userName;
private String password;
@OneToMany(mappedBy = "user")
private List<Role> roles;
//getters and setters..
}
@Entity
public class Role implements Serializable{
@Id
private int id;
private String roleName;
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
//getters and setters..
}
EJB 接口本地
@Local
public interface MyEJBLocal{
public User getUserWithRoles();
}
EJB 类
@Stateless
public class MyEJB implements MyEJBLocal{
@PersistenceContext(unitName ="ANY_NAME")
private EntityManager em;
@Override
public User getUser(){
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> root = cq.from(User.class);
cq.where(cb.equal(root.get(User_.userName),"john"));
User user = em.createQuery(cq).getSingleResult());
em.detach(user); //detaching user object
return user;
}
}
豆类
@Named
public class MyBean implements Serializable{
@EJB
private MyEJBLocal ejb;
public void anyMethod(){
User user = ejb.getUser();
//i will create a list of role just for try to set any role the userJohn
List<Role> roleList = new ArrayList<Role>(2);
roleList.add(new Role(1,'ADMIN'); //creating and adding role 1
roleList.add(new Role(2,'DEVELOPER');//creating and adding role 2
//setting the list of roles created to the user, as you can see the list has 2 values but the value roles of userJohn always is set to null, my setters and getters are correct
userJohn.setRoles(roleList);
user.getRoles(); //<---- HERE THE LIST IS ALWAYS NULL
user.setUserName("new_name");//<--- But this works
}
}
我要做的是克隆我的实体以添加或更改列表值。有人建议我为此使用 DTO,但我不确定我能做什么。
我将不胜感激任何评论。