我是 Hibernate ORM 的新手,我认为您可以帮助我更好地理解它。更准确地说,我发现自己在思考关注点分离是否实现得很好(当然是,我无法理解……但请解释一下)。让我解释一下:在我看来,hibernate 的主要目标是允许开发人员处理忘记数据库特性的类。好的!但是让我们来看看这个案例:
我有一个对象,假设一个 UserDetail 与 Athority 对象有一个可能的关系。
@Entity(name="user")
@Table(name="USERS")
public class User implements UserDetails, DomainObject {
private static final long serialVersionUID = 1L;
private long id;
private String username;
private String password;
Collection<Authority> authorities = new ArrayList<Authority>();
public User() {
super();
}
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id", unique=true, nullable=false)
public long getId() {
return id;
}
//various getters & setters
@OneToMany(mappedBy="user")
public Collection<Authority> getAuthorities() {
return authorities;
}
public void setAuthorities(Collection<Authority> authorities) {
this.authorities = authorities;
}
}
这是权威对象
@Entity(name="authority")
@Table(name="AUTHORITIES")
public class Authority implements GrantedAuthority, DomainObject{
private long id;
private User user;
private String authority; //Spring Security demands them to start with "ROLE_"
public Authority() {
super();
}
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id", unique=true, nullable=false)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@ManyToOne
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Column(name="authority", nullable=false)
public String getAuthority() {
return this.authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
好的,假设我有一个 UserDaoImpl 和 AuthorityDaoImpl (为简洁起见,此处省略)。如果我想创建一个新的 UserDetails 并将其持久化,我必须执行以下操作(它是一个 inizializer bean,但在这里真的无关紧要):
@Component
public class Initializer {
@Autowired
@Qualifier("userDaoImpl")
private UserDao userDao;
@Autowired
@Qualifier("authorityDaoImpl")
private AuthorityDao authorityDao;
@PostConstruct
public void init()
{
if(userDao.loadUserByUsername("admin")==null)
{
System.out.println("starting initialization.");
User admin = new User();
admin.setUsername("admin");
admin.setPassword("admin");
Authority authority = new Authority();
authority.setAuthority("ROLE_ADMIN");
authority.setUser(admin);
admin.getAuthorities().add(authority);
userDao.save(admin);
authorityDao.save(authority);
System.out.println("admin user created.");
}
}
}
好的,我觉得很奇怪,我必须显式调用 AuthorityDao 来保持权威对象。如果关注点分离得到很好的实现,我只需将authority
对象添加到admin
权限列表并单独保留管理员即可。如果我这样做,唯一要保留的实体是管理员。你不觉得一样吗?我错过了什么吗?