我的实体中有一个外键:
@Entity
@Table(name = "role")
public class Role {
@Id
@Column(name = "role_code")
private String code;
@Column(name = "role_lib")
private String lib;
@ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "role_menu" , joinColumns = {@JoinColumn(name = "role_code")} , inverseJoinColumns = {@JoinColumn(name = "menu_id")} )
@JsonManagedReference
private Set<Menu> menus = new HashSet<Menu>();
// getters and setters
}
Hibernate 文档中指出,关系属性应该是 Interface
类型。现在我的问题是在处理此类的实例并使用 getMenus()
方法时:
@Override
@Transactional
public Set<Menu> getListMenu(String role_code) {
return ((Role)get(role_code)).getMenus();
}
我想将其转换为 HashSet ,但我在运行时遇到了持久对象的castException。那么如何使其成为HashSet
呢?
最佳答案
如果 Set
的实现不是 HashSet
,则无法进行转换。但你可以创建一个对象:
new HashSet(obj.getMenus);
但是使用接口(interface)总是比使用实现更好。
这是来自 Hibernate doc 的注释:
Hibernate will actually replace the HashSet with an instance of Hibernate's own implementation of Set. Be aware of the following errors:
......
(HashSet) cat.getKittens(); // Error!
这就是为什么您实际上不需要强制转换也不需要创建新对象:
The persistent collections injected by Hibernate behave like HashMap, HashSet, TreeMap, TreeSet or ArrayList, depending on the interface type.
关于java - 如何从 Set 创建 HashSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44415385/