Java Hibernate:外键的列数错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1483026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 13:19:00  来源:igfitidea点击:

Hibernate: Foreign key has the wrong number of columns

javahibernatespringforeign-keys

提问by niklassaers

I have defined a many-to-many relationship between my two entity classes User and Permission. User has a primary key composite of username and countyId, and my Permission table has a regular integer Id. The table UserPermission has the three foreign keys as its primary key: username, countyId and permissionId.

我在我的两个实体类 User 和 Permission 之间定义了多对多关系。用户有一个由用户名和县名组成的主键,我的权限表有一个常规的整数 ID。UserPermission 表具有三个外键作为其主键:username、countryId 和permissionId。

Since this is a legacy database, I won't have the opportunity to do the Right Thing(?) and make an integer primary key on User.

由于这是一个遗留数据库,我将没有机会做正确的事情(?)并在 User 上创建一个整数主键。

I've defined the many-to-many relationship like this in User.class:

我在 User.class 中定义了这样的多对多关系:

@ManyToMany(targetEntity=Permission.class, cascade={ CascadeType.PERSIST, CascadeType.MERGE } )
@JoinTable(name="tblUserPermission",
joinColumns = { @JoinColumn(name="username"), @JoinColumn(name="countyId") },
inverseJoinColumns = { @JoinColumn(name="permissionId") })
private Collection<Permission> permissions;

Permission.class says this:

Permission.class 是这样说的:

@ManyToMany( cascade = {CascadeType.PERSIST, CascadeType.MERGE}, mappedBy = "permissions", targetEntity = User.class )
private Collection<User> users;

I thought this was the way to go, but when I fire up my Spring context that uses Hibernate 3, I get:

我认为这是要走的路,但是当我启动使用 Hibernate 3 的 Spring 上下文时,我得到:

Caused by: org.hibernate.AnnotationException: A Foreign key refering com.mydomain.data.entities.User from com.mydomain.data.entities.Permission has the wrong number of column. should be 1

What have I done wrong in my annotation? It should be 2, not 1.

我在注释中做错了什么?应该是2,而不是1。



Update:

更新:

Arthur suggested I add referencedColumnName, but that gave me a new exception:

Arthur 建议我添加referencedColumnName,但这给了我一个新的例外:

Caused by: org.hibernate.AnnotationException: referencedColumnNames(username, countyId) of com.mydomain.data.entities.Permission.permissions referencing com.mydomain.data.entities.User not mapped to a single property

On his request, here follow the code: Permission.Class:

根据他的要求,这里遵循代码:Permission.Class:

package com.mydomain.data.entities;

import java.io.Serializable;
import java.util.Collection;
import javax.persistence.*;
import org.hibernate.annotations.ForeignKey;

@Entity
@Table(name = "tblPermission")
public class Permission extends PublishableEntityImpl implements Serializable, Cloneable {

    private static final long serialVersionUID = 7155322069731920447L;

    @Id
    @Column(name = "PermissionId", length = 8, nullable = false)
    private String PermissionId = "";

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "CountyId", nullable = false)
    @ForeignKey(name="FK_CountyID")
    private County county;

    @Column(name = "Permission", nullable = true)
    private Integer permission = 1;

    @ManyToMany( cascade = {CascadeType.PERSIST, CascadeType.MERGE},
             mappedBy = "Permissions",
             targetEntity = Item.class )
    private Collection<Item> items;

    @ManyToMany( cascade = {CascadeType.PERSIST, CascadeType.MERGE},
             mappedBy = "Permissions",
             targetEntity = User.class )
    private Collection<User> users;

    /** Getters and Setters **/
}

and User.class

和 User.class

package com.mydomain.data.entities;

import java.util.*;
import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.annotations.ForeignKey;
import org.hibernate.annotations.IndexColumn;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

@Entity
@Table(name = "tblUser")
public class User extends PublishableEntityImpl implements Serializable, Cloneable {

    @Id
    @Column(name = "CountyId", nullable = false)
    private Integer countyId;

    @Id
    @Column(name = "Username", length = 25, nullable = false)
    private String username;

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name = "CountyId", nullable = false, insertable=false, updatable=false)
    @ForeignKey(name="FK_CountyID")
    private County county;

    @Column(name = "Name", length = 50, nullable = true)
    private String name;

    @Column(name = "Password", length = 30, nullable = true)
    private String password;

    @Column(name = "Role", nullable = false)
    private Integer role;

    @ManyToMany(targetEntity=Permission.class,
            cascade={ CascadeType.PERSIST, CascadeType.MERGE } )
    @JoinTable(name="tblUserPermission",
            joinColumns = { @JoinColumn(name="Username", referencedColumnName="Username"), @JoinColumn(name="CountyId", referencedColumnName="CountyId") },
            inverseJoinColumns = { @JoinColumn(name="PermissionId", referencedColumnName="PermissionId") })
   private Collection<Permission> permissions;

    @OneToMany(fetch=FetchType.LAZY, mappedBy="county")
    @IndexColumn(name="version")
    private List<Version> versions;

    /** Getters and setters **/
}

Cheers

干杯

Nik

尼克

采纳答案by Arthur Ronald

In order to solve referencedColumnName exception

为了解决referencedColumnName异常

In User put

在用户放置

@ManyToMany(cascade={CascadeType.PERSIST, cascadeType.MERGE})
private Collection<Permission> permissions;

And in Permission

并在许可中

@ManyToMany(mappedBy="permissions")
@JoinTable(name="tblUserPermission",
 joinColumns={@JoinColumn(name="permissionId", referencedColumnName="permissionId")},
 inverseJoinColumns={
 @JoinColumn(name="username", referencedColumnName="username"),                         
 @JoinColumn(name="countyId", referencedColumnName="countyId")})
private Collection<User> users;

UserId class

用户 ID 类

public class UserId implements Serializable {

    private String username;

    private Integer countyId;

    // getter's and setter's

    public boolean equals(Object o) {

        if(o == null)
            return false;

        if(!(o instanceof UserId))
            return false;

        UserId id = (UserId) o;
        if(!(getUsername().equals(id.getUsername()))
            return false;

        if(!(getCountyId().equals(id.getCountyId()))
            return false;

        return true;
    }

    public int hachcode() {
       // hashcode
    }

}

Then in User class put

然后在用户类中放置

@Entity
@Table(name="tblUser")
@IdClass(UserId.class)
public class User ... {

    @Id
    private String username;

    @Id
    private Integer countyId;

}

regards,

问候,