Annotation用起来真是太方便了,多对多映射很需要很少的几个注解就可以搞定.
需要的jar包是ejb3-persistence.jar(见附件)
实例:
用户表:user
CREATE TABLE user(
id BIGINT NOT NULL,
optimistic INT,
userName VARCHAR(32),
password VARCHAR(128),
PRIMARY KEY (id)
);
角色表
CREATE TABLE role(
id BIGINT NOT NULL,
optimistic INT,
name VARCHAR(50),
active SMALLINT NOT NULL,
PRIMARY KEY (id)
);
角色用户关系表
CREATE TABLE roles2users(
users_fk BIGINT,
roles_fk BIGINT
)
关系表不要映射成实体,也就是说我们的java代码只有2个类,user类和role类。
[b]java代码[/b]
user对象和role对象都继承自同一个父类,父类封装了id和hibernate版本控制的字段还有equals和hashcode方法:
@MappedSuperclass
public class AutoIDEntity implements java.io.Serializable{
private static final long serialVersionUID = 1L;
private Long id;
private Integer optimistic;
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE,generator="SEQ_STORE")
public Long getId() {
return this.id;
}
@Version
public Integer getOptimistic() {
return this.optimistic;
}
protected void setId(Long id) {
this.id = id;
}
protected void setOptimistic(Integer optimistic) {
this.optimistic = optimistic;
}
@Override
public boolean equals(final Object other) {
if (!(other instanceof AutoIDEntity))
return false;
AutoIDEntity castOther = (AutoIDEntity) other;
return new EqualsBuilder().append(id, castOther.getId()).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(id).toHashCode();
}
}
[b]User类[/b][size=small][/size]
@Entity
@org.hibernate.annotations.Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@SequenceGenerator(
name="SEQ_STORE",
sequenceName="user_id_sequence"
)
public class User extends AutoIDEntity {
/**
* 登录名
*/
private String userName;
/**
* 密码
*/
private String password;
/**
* 角色集合
*/
private Set<Role> roles = new HashSet<Role>();
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "ROLES2USERS",
joinColumns = {
@JoinColumn(name = "USERS_FK", nullable = false, insertable = true, updatable = true, columnDefinition = "BIGINT")
},
inverseJoinColumns = {
@JoinColumn(name = "ROLES_FK", nullable = false, insertable = true, updatable = true, columnDefinition = "BIGINT")
}
)
public Set<Role> getRoles() {
return this.roles;
}
//省略getter和setter方法
}
[b]角色实体[/b][size=medium][/size]
@Entity
@org.hibernate.annotations.Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@SequenceGenerator(
name="SEQ_STORE",
sequenceName="role_id_sequence"
)
public class Role extends AutoIDEntity {
/**
* 角色名
*/
private String name;
/**
* 用户集合
*/
private Set<User> users = new HashSet<User>();
/**
* 该角色的状态,1为有效,0为无效
*/
private boolean active = true;
@ManyToMany(fetch = FetchType.LAZY,mappedBy="roles")
public Set<User> getUsers() {
return users;
}
//省略其它的getter和setter方法
}