weixin_37467879
2017-02-07 02:41
采纳率: 100%
浏览 1.5k
已采纳

求助:hibernate联合主键 (注解),测试时一直报null

@Entity
@Table(name="SysRoleResource")
@IdClass(value=RoleResourcePK.class)
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler"})
public class RoleResource implements Serializable{
private static final long serialVersionUID = 6109494575468275047L;
private Integer RoleId;
private Integer ResourceId;
@Id
@Column(length=10,name="RoleId")
public Integer getRoleId() {
return RoleId;
}
public void setRoleId(Integer roleId) {
RoleId = roleId;
}
@Id
@Column(length=10,name="ResourceId")
public Integer getResourceId() {
return ResourceId;
}
public void setResourceId(Integer resourceId) {
ResourceId = resourceId;
}
@Override
public String toString() {
return "RoleResource [RoleId=" + RoleId + ", ResourceId=" + ResourceId
+ "]";
}
}//实体类

//主键类
public class RoleResourcePK implements Serializable{

private static final long serialVersionUID = -3149726451195304787L;
private Integer RoleId;
private Integer ResourceId;
public Integer getRoleId() {
    return RoleId;
}
public void setRoleId(Integer roleId) {
    RoleId = roleId;
}
public Integer getResourceId() {
    return ResourceId;
}
public void setResourceId(Integer resourceId) {
    ResourceId = resourceId;
}
@Override
public String toString() {
    return "RoleResourcePK [RoleId=" + RoleId + ", ResourceId="
            + ResourceId + "]";
}
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
            + ((ResourceId == null) ? 0 : ResourceId.hashCode());
    result = prime * result + ((RoleId == null) ? 0 : RoleId.hashCode());
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    RoleResourcePK other = (RoleResourcePK) obj;
    if (ResourceId == null) {
        if (other.ResourceId != null)
            return false;
    } else if (!ResourceId.equals(other.ResourceId))
        return false;
    if (RoleId == null) {
        if (other.RoleId != null)
            return false;
    } else if (!RoleId.equals(other.RoleId))
        return false;
    return true;
}

}
//测试
@Test
public void add(){
RoleResource rr=new RoleResource();
rr.setResourceId(2);
rr.setRoleId(1);
try {
rs.save(rr);
System.out.println("添加成功"+JSON.toJSONString(rr));
} catch (Exception e) {
System.out.println("添加失败"+e.getMessage());
}
}
测试时一直报null
org.springframework.orm.hibernate4.HibernateTransactionManager.afterPropertiesSet(360) | Using DataSource [com.mchange.v2.c3p0.ComboPooledDataSource[ identityToken -> 1hgeest9m680zit10ue8ko|72534f6f, dataSourceName -> 1hgeest9m680zit10ue8ko|72534f6f ]] of Hibernate SessionFactory for HibernateTransactionManager
null
添加失败null

这是我的数据源配置及 sessionFactory配置

destroy-method="close">

<!-- 请求超时时间 -->
<property name="checkoutTimeout" value="30000" />
<!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
<property name="idleConnectionTestPeriod" value="30" />
<!-- 连接数据库连接池最大空闲时间 -->
<property name="maxIdleTime" value="30" />
<!-- 连接池初始化连接数 -->
<property name="initialPoolSize" value="5" />
<property name="minPoolSize" value="5" />
<property name="maxPoolSize" value="20" />
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
<property name="acquireIncrement" value="5" />

class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 注入数据源 相关信息看源码 -->

<!-- hibernate配置信息 -->


${hibernate.dialect}
${hibernate.show_sql}
${hibernate.format_sql}
${hibernate.hbm2ddl.auto}
true

        <!-- 开启二级缓存 ehcache -->
        <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
        <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
        <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
        <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}
        </prop>
    </props>
</property>
<!-- 扫描hibernate注解配置的entity -->
<property name="packagesToScan" value="cn.com.topsoft.entity" />

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

4条回答 默认 最新

  • 桐小目 2017-02-07 08:24
    已采纳

    建表语句

     create table user_relation (
        user_id_a int not null,
        user_id_b int not null,
        relation_status int not null,
        relation_start datetime,
        primary key(user_id_a,user_id_b),
        foreign key (user_id_a) references user_main(user_id),
        foreign key (user_id_b) references user_main(user_id)
    )
    

    前两个是联合主键
    实体类UserRelation.java

     package com.main.entity;
    
    
    import java.sql.Timestamp;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.IdClass;
    import javax.persistence.Table;
    
    import com.alibaba.fastjson.annotation.JSONField;
    
    /*
     * http://blog.csdn.net/robinpipi/article/details/7655388
     */
    
    @Entity
    @Table(name="user_relation")
    @IdClass(value=UserRelationPriKey.class)
    public class UserRelation{
        private int userIdA;
        private int userIdB;
        private int relationStatus;
        private Timestamp relationStart;
        @Id
        @Column(name="user_id_a")
        public int getUserIdA() {
            return userIdA;
        }
        public void setUserIdA(int userIdA) {
            this.userIdA = userIdA;
        }
        @Id
        @Column(name="user_id_b")
        public int getUserIdB() {
            return userIdB;
        }
        public void setUserIdB(int userIdB) {
            this.userIdB = userIdB;
        }
        @Column(name="relation_status")
        public int getRelationStatus() {
            return relationStatus;
        }
        public void setRelationStatus(int relationStatus) {
            this.relationStatus = relationStatus;
        }
        @Column(name="relation_start")
        @JSONField (format="yyyy-MM-dd HH:mm:ss")
        public Timestamp getRelationStart() {
            return relationStart;
        }
        public void setRelationStart(Timestamp relationStart) {
            this.relationStart = relationStart;
        }
    
    }
    
    

    联合主键配置类UserRelationPriKey.java

     package com.main.entity;
    
    import java.io.Serializable;
    
    public class UserRelationPriKey implements Serializable{
        /**
         * UserRelation的联合主键
         */
        private static final long serialVersionUID = 1L;
        private int userIdA;
        private int userIdB;
    
        public int getUserIdA() {
            return userIdA;
        }
        public void setUserIdA(int userIdA) {
            this.userIdA = userIdA;
        }
        public int getUserIdB() {
            return userIdB;
        }
        public void setUserIdB(int userIdB) {
            this.userIdB = userIdB;
        }
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + userIdA;
            result = prime * result + userIdB;
            return result;
        }
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            UserRelationPriKey other = (UserRelationPriKey) obj;
            if (userIdA != other.userIdA)
                return false;
            if (userIdB != other.userIdB)
                return false;
            return true;
        }
    }
    
    

    spring hibernate datasource配置

     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="classpath:config/jdbc.properties" />
        </bean>
    
        <!-- 配置数据源 -->
        <bean id="dataSource"
            class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName" value="${driverClassName}"></property>
            <property name="url" value="${url}"></property>
            <property name="username" value="${userName}"></property>
            <property name="password" value="${password}"></property>
        </bean>
    

    hibernate session配置

     <!-- 配置 hibernate session -->
    
        <bean id="sessionFactory"
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                    <prop key="hibernate.hbm2ddl.auto">update</prop>  
                    <prop key="hibernate.show_sql">true</prop>  
                    <prop key="hibernate.format_sql">true</prop>
    
                    <prop key="hibernate.cache.use_second_level_cache">false</prop>
                    <prop key="hibernate.cache.use_query_cache">false</prop>
                    <prop key="current_session_context_class">thread</prop>
                    <prop key="hibernate.current_session_context_calss">org.springframework.orm.hibernate4.SpringSessionContext</prop>
                </props>
            </property>
            <property name="packagesToScan">  
                <list>  
                    <value>com.main.entity</value>  
                </list>  
            </property>  
        </bean>
    

    这样配置在我的项目中是能够正常增删改查的,我参考的博客是entity里面的那个链接,看了几遍你的代码眼拙看不出什么名堂,慢慢测试总能解决的,祝顺利~

    已采纳该答案
    打赏 评论
  • 桐小目 2017-02-07 04:53

    我正好在做项目时也用了hibernate注解的联合主键,配置的方法和你一样的,没有出现错误。和你的对照了一下,你配置的联合主键应该是没有任何问题的(如果中间没有出现写错字母的情况的话)。看你下面报错报的错误是数据源(datasource)的错误,应该不是这里联合主键的错误,你最好再检查一下数据源配置是否正确。
    我把我的数据源配置代码放一下(我用的spring+hibernate),希望对你解决问题有些帮助。hibernate单独配置可以百度一下博客都有,慢慢比对一下。

     <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location" value="classpath:config/jdbc.properties" />
        </bean>
    
        <!-- 配置数据源 -->
        <bean id="dataSource"
            class="org.apache.commons.dbcp.BasicDataSource">
            <property name="driverClassName" value="${driverClassName}"></property>
            <property name="url" value="${url}"></property>
            <property name="username" value="${userName}"></property>
            <property name="password" value="${password}"></property>
        </bean>
    

    其中具体数据是放在了jdbc.properties这个资源文件里面了,如果确认数据源没问题的话最好再看一下sessionFactory配置是否正确。

    打赏 评论
  • JE_GE 2017-02-07 05:27
    打赏 评论
  • weixin_37467879 2017-02-07 06:48

    这是我的数据源配置及 sessionFactory配置

    <!-- 配置数据源 c3p0 -->
    destroy-method="close">



        <!-- 请求超时时间 -->
        <property name="checkoutTimeout" value="30000" />
        <!-- 每60秒检查所有连接池中的空闲连接。默认值: 0,不检查 -->
        <property name="idleConnectionTestPeriod" value="30" />
        <!-- 连接数据库连接池最大空闲时间 -->
        <property name="maxIdleTime" value="30" />
        <!-- 连接池初始化连接数 -->
        <property name="initialPoolSize" value="5" />
        <property name="minPoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3 -->
        <property name="acquireIncrement" value="5" />
    </bean>
    
    <!-- 配置hibernate的SessionFactory -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- 注入数据源 相关信息看源码 -->
        <property name="dataSource" ref="dataSource" />
        <!-- hibernate配置信息 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.enable_lazy_load_no_trans">true</prop>
    
                <!-- 开启二级缓存 ehcache -->
                <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>
                <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
                <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>
                <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}
                </prop>
            </props>
        </property>
        <!-- 扫描hibernate注解配置的entity -->
        <property name="packagesToScan" value="cn.com.topsoft.entity" />
    
    </bean>
    
    打赏 评论