设为首页 - 加入收藏 焦点技术网
热搜:java
当前位置:首页 >

hibernate 多对多代码

2013-08-21 22:49:00.0 随笔  
导读:没事干,决定学习一下hibernate,测试了一下多对多单向关联,把代码贴出来,以备以后用。使用的maven创建项目,pom.xml: 4.0.0 com.mxy hibernatetest 0.0.1-SNAPSHOT jar hibernatetest http://maven.apache.org UTF-8 org.hibernate hiber...。。。

没事干,决定学习一下hibernate,测试了一下多对多单向关联,把代码贴出来,以备以后用。

使用的maven创建项目,pom.xml:

  4.0.0  com.mxy  hibernatetest  0.0.1-SNAPSHOT  jar  hibernatetest  http://maven.apache.org      UTF-8          org.hibernate  hibernate-core  4.2.4.Final    mysql  mysql-connector-java  5.1.26           junit      junit      4.10      test      

hibernate.cfg.xml

                    com.mysql.jdbc.Driver        jdbc:mysql://localhost/hibernate        root        password                1                org.hibernate.dialect.MySQL5Dialect                thread                org.hibernate.cache.internal.NoCacheProvider                true        true                update                                            

java类,User

package com.mxy.entity;import javax.persistence.CascadeType;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.JoinColumn;import javax.persistence.ManyToOne;@Entitypublic class User { @Id @GeneratedValue private int id; private String username; private String password; @ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE},targetEntity=Role.class) @JoinColumn(name="roleid") private Role role;  public Role getRole() {  return role; } public void setRole(Role role) {  this.role = role; } public int getId() {  return id; } public void setId(int id) {  this.id = id; } public String getUsername() {  return username; } public void setUsername(String username) {  this.username = username; } public String getPassword() {  return password; } public void setPassword(String password) {  this.password = password; } }

Role

package com.mxy.entity;import java.util.Set;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.ManyToMany;@Entitypublic class Role {  @Id @GeneratedValue private int id; private String rolename; @ManyToMany private Set permissions; public Set getPermissions() {  return permissions; } public void setPermissions(Set permissions) {  this.permissions = permissions; } public int getId() {  return id; } public void setId(int id) {  this.id = id; } public String getRolename() {  return rolename; } public void setRolename(String rolename) {  this.rolename = rolename; }  }

Permission

package com.mxy.entity;import java.util.Set;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.ManyToMany;@Entitypublic class Permission {  @Id @GeneratedValue private int id; private String permission; public int getId() {  return id; } public void setId(int id) {  this.id = id; } public String getPermission() {  return permission; } public void setPermission(String permission) {  this.permission = permission; } }


测试类:

package com.mxy.hibernatetest;import java.util.HashSet;import java.util.Set;import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;import org.junit.AfterClass;import org.junit.BeforeClass;import com.mxy.entity.Permission;import com.mxy.entity.Role;import com.mxy.entity.User;public class Test {  private static SessionFactory sessionFactory; private static Session session;  @BeforeClass public static void beforeClass() {   sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();   session = sessionFactory.getCurrentSession();   session.beginTransaction(); } @AfterClass public static void afterClass() {  session.getTransaction().commit();  sessionFactory.close(); } @org.junit.Test public void TestM2M(){    Role role = new Role();  role.setRolename("userq");  Permission per = new Permission();  per.setPermission("lookq");  Set pers = new HashSet();  pers.add(per);  role.setPermissions(pers);    session.save(per);  session.save(role);     }  @org.junit.Test public void TestM2M_DELETE(){    Role role = (Role)session.createQuery("from Role role where role.id = '2'").list().get(0);    session.delete(role); }  @org.junit.Test public void TestUserSave(){  User u = new User();  u.setUsername("xxx");  session.save(u); }  @org.junit.Test public void TestUpdateUser(){  Role role = new Role();    role.setRolename("test");    User u = (User)session.createQuery("from User user where user.id = '1'").list().get(0);  u.setRole(role);    session.save(role);    session.update(u); }  @org.junit.Test public void TestInsertPermissionsToRole(){  Role role = (Role)session.createQuery("from Role role where role.id = '1'").list().get(0);    Set pers = new HashSet();    for(int i = 0;i < 9;i++){   Permission per = new Permission();   per.setPermission("permission" + i);      pers.add(per);   session.save(per);  }    role.setPermissions(pers);    session.update(role); }  @org.junit.Test public void TestDeletePermission(){  Permission per = (Permission)session.createQuery("from Permission per where per.id = '4'").list().get(0);    session.delete(per); }}

遇到的问题:

1 在使用注解的时候,不能部分加到字段上,部分加到getXXX方法上,需要统一,要不会报错。

2 Role与Permission是多对多的关系,Role是主控方,当想在Permission删除的时候,会报错,显示外键约束,这是我们可以将数据库中role_permission中的对于permission表外键id引用的删除时候的约束改为cacade。我使用的是navicat for mysql,右击role_permission--》设计表--》外键--》删除时,改为cascade。

3 mappedBy配置的是被控方,值为主控方中对应的字段的名字。

(编辑: mengxiangyue)

网友评论
相关文章