日期:2014-05-17  浏览次数:20837 次

hibernate 多对多单向映射 中间表没插入数据
User表 hibernate文件
<class name="User" table="user" catalog="exam">
  <id name="id" type="java.lang.Integer">
  <column name="id" />
  <generator class="native" />
  </id>
  <property name="name" type="java.lang.String">
  <column name="name" length="32" not-null="true" />
  </property>
  <property name="password" type="java.lang.String">
  <column name="password" length="32" not-null="true" />
  </property>
  <set name="roles" table="user_role" cascade="save-update" lazy="true">
  <key column="userid"></key>
  <many-to-many class="Role" column="roleid"></many-to-many>
  </set>
</class>
Role表 hibernate文件
<hibernate-mapping>
  <class name="Role" table="role" catalog="exam">
  <id name="id" type="java.lang.Integer">
  <column name="id" />
  <generator class="native" />
  </id>
  <property name="name" type="java.lang.String">
  <column name="name" length="32" not-null="true" />
  </property>
  </class>
</hibernate-mapping>
bean文件
public class User implements java.io.Serializable {

// Fields

private Integer id;
private String name;
private String password;
private Set roles;

// Constructors

/** default constructor */
public User() {
}

/** full constructor */
public User(String name, String password) {
this.name = name;
this.password = password;
}

// Property accessors

public Integer getId() {
return this.id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public String getPassword() {
return this.password;
}

public void setPassword(String password) {
this.password = password;
}

public Set getRoles() {
return roles;
}

public void setRoles(Set roles) {
this.roles = roles;
}


}
public class Role implements java.io.Serializable {

// Fields

private Integer id;
private String name;

// Constructors

/** default constructor */
public Role() {
}

/** full constructor */
public Role(String name) {
this.name = name;
}

// Property accessors

public Integer getId() {
return this.id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}





}
在action中进行的操作
Role role1 = new Role();
role1.setName("22222");
Role role2 = new Role();
role2.setName("33333");
Role role3 = new Role();
role3.setName("44444");