首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

SQLGrammarException:could not initialize a collection:解决方法

2012-12-21 
SQLGrammarException:could not initialize a collection:hibernate异常:org.hibernate.exception.SQLGram

SQLGrammarException:could not initialize a collection:
hibernate异常:org.hibernate.exception.SQLGrammarException: could not initialize a collection: could not initialize a collection: [com.net.sys.entity.Net_User.Net_Roles#1] 

问题是这样的,我在做一个登陆模块,开始没有设置多对多关系的时候一切正常,可以正常登录,但是在.hbm.xml设置了many to many 关系之后,就会出现这个异常,奇怪的是控制台的执行语句为:Hibernate: select net_roles0_.user_id as user1_1_, net_roles0_.role_id as role2_1_, net_role1_.id as id2_0_, net_role1_.role_name as role2_2_0_ from Net_RoleToUser net_roles0_, Net_role net_role1_ where net_roles0_.role_id=net_role1_.id(+) and net_roles0_.user_id=?  亮点是(+)

下面贴出文件,按照entity ,action  ,service ,dao 的顺序:

Net_User ----用户的实体类---很有可能是问题的出现所在


public class Net_User implements java.io.Serializable {

// Fields

private Integer id;
private String username;
private String password;
private Set  Net_Roles = new HashSet(0);


// Constructors

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

/** full constructor */
public Net_User(String username, String password) {
this.username = username;
this.password = password;
this.Net_Roles=Net_Roles;
}

// Property accessors

public Set<Net_Role> getNet_Roles() {
return Net_Roles;
}

public void setNet_Roles(Set netRoles) {
Net_Roles = netRoles;
}

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

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

public String getUsername() {
return this.username;
}

public void setUsername(String username) {
this.username = username;
}

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

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

}



Net_Role----权限的实体类,这个类应该不是问题的关键

public class Net_Role implements java.io.Serializable {

// Fields

private Integer id;
private String roleName;
private Set<Net_User> Net_Users = new HashSet(0);

// Constructors

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

/** full constructor */
public Net_Role(String roleName) {
this.roleName = roleName;
this.Net_Users=Net_Users;
}

// Property accessors

public Set<Net_User> getNet_Users() {
return Net_Users;
}

public void setNet_Users(Set<Net_User> netUsers) {
Net_Users = netUsers;
}

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

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

public String getRoleName() {
return this.roleName;
}

public void setRoleName(String roleName) {
this.roleName = roleName;


}

@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
if(obj instanceof Net_Role){
Net_Role role2=(Net_Role)obj;
return id.equals(role2.getId());
}else{
return false;
}
}

@Override
public int hashCode() {
// TODO Auto-generated method stub
return id.hashCode();
}

}



Net_User.hbm.xml---当我把下面的many to many 打上注释,可以正常运行了,打开注释,报以上异常


<hibernate-mapping>
    <class name="com.net.sys.entity.Net_User" table="Net_sysuser" >
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity"></generator>
        </id>
        <property name="username" type="java.lang.String">
            <column name="username" length="100" />
        </property>
        <property name="password" type="java.lang.String">
            <column name="password" length="100" />
        </property>
        <!-- 
        <set name="Net_Roles" table="Net_RoleToUser" cascade="all" inverse="true" >
            <key>
                <column name="user_id" length="50" />
            </key>
            <many-to-many   class="com.net.sys.entity.Net_Role" >
                <column name="role_id" length="50" />
            </many-to-many>
        </set>
        -->


Net_Role.hbm.xml


<hibernate-mapping>
    <class name="com.net.sys.entity.Net_Role" table="Net_role"  >
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity"></generator>
        </id>
        <property name="roleName" type="java.lang.String">
            <column name="role_name" length="50" />
        </property>
     
        <set name="Net_Users" inverse="true" table="Net_RoleToUser" cascade="all" >


            <key>
                <column name="role_id" length="50" />
            </key>
            <many-to-many  class="com.net.sys.entity.Net_User"   >
                <column name="user_id" length="50" />
            </many-to-many>
        </set>
          
       </class>
</hibernate-mapping>




LoginAction

public class LoginAction extends ActionSupport {

private String username;

private String password;

private Net_User_Service netUserService;

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;
}

public Net_User_Service getNetUserService() {
return netUserService;
}

public void setNetUserService(Net_User_Service netUserService) {
this.netUserService = netUserService;
}

public String execute() {
// System.out.println("bomm !");
Net_User netUser = netUserService.autheication(username, password);
// System.out.println("   ~");
if (netUser == null) {
return "fail";
}
ServletActionContext.getRequest().getSession().setAttribute("user", netUser);
    Set<Net_Role> roleSet = netUser.getNet_Roles();
    for (Net_Role netRole : roleSet) {
    System.out.println(roleSet);

}

return "success";
}

}



Net_User_Service

package com.net.sys.service;

import java.util.List;

import com.net.sys.entity.Net_User;
import com.net.sys.dao.Net_User_Dao;;

public class Net_User_Service {

private Net_User_Dao netUserDao;


public void setNetUserDao(Net_User_Dao netUserDao) {
this.netUserDao = netUserDao;
}



public Net_User autheication(String username, String password) {
List<Net_User> userlist =netUserDao.findByUsername(username);
for (Net_User netUser : userlist) {
if (netUser.getPassword().equals(password)) {
return netUser;
}
}
return null;
}


}




dao不写了,自动生成的,CSDN提示我帖子太长了。。。
[最优解释]
引用:
引用:
在many to many 关系中需要指定主从关系


<set name="Net_Roles" table="Net_RoleToUser" cascade="all" inverse="true" >

<set name="Net_Users" inverse="true" table="Net_RoleToUser" cascade="all" >

in……


cascade也不要都设置为all
[其他解释]
配置文件看看有没有问题,去看看表 外键关系是否错误
[其他解释]
你看一下 有没Net_User中的roleId不存在role表中 
[其他解释]
在many to many 关系中需要指定主从关系
<set name="Net_Roles" table="Net_RoleToUser" cascade="all" inverse="true" >

<set name="Net_Users" inverse="true" table="Net_RoleToUser" cascade="all" >

inverse设置其中一个为true,另一个为false看看
[其他解释]
引用:
你看一下 有没Net_User中的roleId不存在role表中


role的表
[img=http://a109.photo.store.qq.com/psb?/V139GSiK3nH1JF/Z.U0gJYkEhKSbsYtEffSR5VXkO8paiSoRE*sCJgHzVY!/i/dLBnB0GZHAAA&bo=WAGLAAAAAAABAPU!][/img]

Net_User的表
[img=http://b108.photo.store.qq.com/psb?/V139GSiK3nH1JF/hwMhraLkc93Rcv*kVwVecTLQjzmr0uuceDgLU9SdjPw!/b/dIHObkAUMgAA&bo=.gGSAAAAAAABAE4!][/img]

roletouser 表
[img=http://b122.photo.store.qq.com/psb?/V139GSiK3nH1JF/xO9Qw1c0JLUI7V2KWaIAAxxHQ9b0ElnBRTsnMxYez4s!/b/dIruvUjdCwAA&bo=vwG6AAAAAAADACE!][/img]
[其他解释]
引用:
你看一下 有没Net_User中的roleId不存在role表中


这版权让腾讯搞的,呵呵,我试试啊
[其他解释]
引用:
在many to many 关系中需要指定主从关系
<set name="Net_Roles" table="Net_RoleToUser" cascade="all" inverse="true" >

<set name="Net_Users" inverse="true" table="Net_RoleToUser" cascade="all" >

inverse设置其中一个为t……



还是一样,郁闷啊,就是.hbm.xml 或者实体类的问题了
[其他解释]
引用:
引用:
引用:
在many to many 关系中需要指定主从关系
<set name="Net_Roles" table="Net_RoleToUser" cascade="all" inverse="true" >

<set name="Net_Users" inverse="true" table="Net_RoleToUser" cascade=……


还是不行,many to many 我的数据库表用不用设置外键呢? 有一个类无法实例化,纠结啊
[其他解释]
引用:
引用:
引用:
在many to many 关系中需要指定主从关系
<set name="Net_Roles" table="Net_RoleToUser" cascade="all" inverse="true" >

<set name="Net_Users" inverse="true" table="Net_RoleToUser" cascade=……



找到问题所在了,两个实体类缺少构造方法

 /** full constructor */
    public Net_User(String username, String password,XXXXX) {
        this.username = username;
        this.password = password;
        this.Net_Roles=Net_Roles;
    }






之后分别把many to many 的Net_RoleToUser 的两个字段分别设置了外键,可以了,但是在Action的for循环出现问题了,


ServletActionContext.getRequest().getSession().setAttribute("user", netUser);
    Set<Net_Role> roleSet = netUser.getNet_Roles();
    System.out.println("good !");
//    for (Net_Role netRole : roleSet) {
//    System.out.println(roleSet);
//
//}


打开注释就报相同的错误,加上注释可以执行
[其他解释]
引用:
引用:
引用:
引用:
在many to many 关系中需要指定主从关系
<set name="Net_Roles" table="Net_RoleToUser" cascade="all" inverse="true" >

<set name="Net_Users" inverse="true" table="Net_RoleTo……

看一下roleSet的值,我还是感觉 有数据不正常导致的,或者 你的dao发出来看看?
[其他解释]
引用:
引用:引用:
引用:
引用:
在many to many 关系中需要指定主从关系
<set name="Net_Roles" table="Net_RoleToUser" cascade="all" inverse="true" >

<set name="Net_Us……



public class Net_Role_Dao  extends HibernateDaoSupport{

private static final Log log = LogFactory.getLog(Net_Role_Dao.class);
// property constants
public static final String NAME = "name";

protected void initDao() {
// do nothing
}

public void save(Net_Role transientInstance) {
log.debug("saving Net_Role instance");
try {
getHibernateTemplate().save(transientInstance);
log.debug("save successful");
} catch (RuntimeException re) {
log.error("save failed", re);
throw re;
}
}

public void delete(Net_Role persistentInstance) {
log.debug("deleting Net_Role instance");
try {
getHibernateTemplate().delete(persistentInstance);
log.debug("delete successful");
} catch (RuntimeException re) {
log.error("delete failed", re);
throw re;
}
}

public Net_Role findById(java.lang.String id) {
log.debug("getting Net_Role instance with id: " + id);
try {
Net_Role instance = (Net_Role) getHibernateTemplate().get(
"com.net.sys.entity.Net_Role", id);
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}

public List findByExample(Net_Role instance) {
log.debug("finding Net_Role instance by example");
try {
List results = getHibernateTemplate().findByExample(instance);
log.debug("find by example successful, result size: "
+ results.size());
return results;
} catch (RuntimeException re) {
log.error("find by example failed", re);
throw re;
}
}

public List findByProperty(String propertyName, Object value) {


log.debug("finding Net_Role instance with property: " + propertyName
+ ", value: " + value);
try {
String queryString = "from Net_Role as model where model."
+ propertyName + " = ? "  + " ";
return getHibernateTemplate().find(queryString, value);
} catch (RuntimeException re) {
log.error("find by property name failed", re);
throw re;
}
}

public List findByName(Object name) {
return findByProperty(NAME, name);
}

public List findAll() {
log.debug("finding all Net_Role instances");
try {
String queryString = "from Net_Role";
return getHibernateTemplate().find(queryString);
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}

public Net_Role merge(Net_Role detachedInstance) {
log.debug("merging Net_Role instance");
try {
Net_Role result = (Net_Role) getHibernateTemplate().merge(
detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}

public void attachDirty(Net_Role instance) {
log.debug("attaching dirty Net_Role instance");
try {
getHibernateTemplate().saveOrUpdate(instance);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}

public void attachClean(Net_Role instance) {
log.debug("attaching clean Net_Role instance");
try {
getHibernateTemplate().lock(instance, LockMode.NONE);
log.debug("attach successful");
} catch (RuntimeException re) {
log.error("attach failed", re);
throw re;
}
}

public static Net_Role_Dao getFromApplicationContext(ApplicationContext ctx) {
return (Net_Role_Dao) ctx.getBean("Net_Role_Dao");
}

}


[其他解释]
来结贴了,这个项目思路有问题,重新开始了!!!

热点排行