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

求助: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里面的那个链接,看了几遍你的代码眼拙看不出什么名堂,慢慢测试总能解决的,祝顺利~

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料