Role
package com
import java
public class Role {
private int id;
private String name;
private Set<User> users;
public int getId() {
return id;
}
public void setId(int id) {
this
}
public String getName() {
return name;
}
public void setName(String name) {
this
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this
}
}
User
package com
import java
public class User {
private int id;
private String name;
private Set<Role> roles;
public int getId() {
return id;
}
public void setId(int id) {
this
}
public String getName() {
return name;
}
public void setName(String name) {
this
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this
}
}
映射文件
Role
<?xml version=
<!DOCTYPE hibernate
hiber/hibernate
<hibernate
<class name=
<id name=
<generator class=
</id>
<property name=
<set name=
<key>
<column name=
</key>
<many
</set>
</class>
</hibernate
User
<?xml version=
<!DOCTYPE hibernate
<hibernate
<class name=
<id name=
<generator class=
</id>
<property name=
<set name=
<key>
<column name=
</key>
<many
</set>
</class>
</hibernate
導出的sql
create table Hibernate_Many
id integer not null auto_increment
name varchar(
primary key (id)
)
create table Hibernate_Many
id integer not null auto_increment
name varchar(
primary key (id)
)
create table user_role (
role_id integer not null
user_id integer not null
primary key (user_id
)
alter table user_role
add index FK
add constraint FK
foreign key (role_id)
references Hibernate_Many
alter table user_role
add index FK
add constraint FK
foreign key (user_id)
references Hibernate_Many
測試代碼
@Test
public void insert(){
Session session=HibernateSessionFactory
Transaction transaction=session
try {
transaction
User user=new User();
user
Role role=new Role();
role
Set<Role> roles=new HashSet<Role>();
roles
user
session
mit();
} catch (HibernateException e) {
e
transaction
}
}
@Test
public void select(){
Session session=HibernateSessionFactory
User user=(User) session
System
Set<Role> roles=user
for (Iterator<Role> iterator = erator(); iterator
Role role = (Role) iterator
System
}
}
From:http://tw.wingwit.com/Article/program/Java/ky/201311/28194.html