JPA复合外键主键

时间:2018-05-14 08:47:56

标签: java mysql spring hibernate jpa

所以我目前有一个包含用户信息的数据库,用户定义的用户是user_id。

然后我有一个名为token的表,它有一个token_id和user_id作为主键和其他信息,使这成为一个到多个数据库。

@Entity
@Table(name = "user")
public class User implements Serializable {
    @Id
    @Column(name = "user_id")
    private long userId;
    //Other variables and getters and setters

    @OneToMany(orphanRemoval = true, mappedBy = "user", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    @Access(AccessType.PROPERTY) //I need this as is since I have other things in the setter 
    private List<Token> tokens = new ArrayList<>();

    public List<Token> getTokens() {
        return tokens;
    }

    public void setTokens(List<Token> tokens) {
        this.tokens = tokens;
    }
}

在这段代码之后,我有了令牌的类

public class Token implements Serializable{
    @Id
    private long tokenId;

    @Id
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    private User user;

    @Column(nullable = false)
    private String token;

    @Access(AccessType.PROPERTY)
    private Instant lastUsed;

    @Column(nullable = false)
    private Instant dateCreated;

    @Transient
    private boolean expired;

    //Getters and setters go here


    //Static methods and generating the token
    private static String generateToken(){
        Random random = new Random();
        byte[] randomString = new byte[256];
        random.nextBytes(randomString);
        return Base64.encodeBase64String(randomString);
    }

    public static Token generateUserToken(User user){
        Token token = new Token();
        token.setTokenId(new Random().nextLong());
        token.setUser(user);
        token.setDateCreated(Instant.now());
        token.setToken(generateToken());

        return token;
    }
    //Static methods and generating the token
}

现在出于某种原因,只要User user没有标记为@Id就可以了(即使在数据库中它是主键)。

任何帮助;

application.properties:

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL57InnoDBDialect

spring.jpa.show-sql=true
logging.level.org.hibernate.type=TRACE

SQL输出:

Hibernate: insert into tokens (date_created, last_used, token, user_id, token_id) values (?, ?, ?, ?, ?)
binding parameter [1] as [TIMESTAMP] - [2018-05-14T08:29:00.719764Z]
binding parameter [2] as [TIMESTAMP] - [null] //This is okay to be null this is last_used
binding parameter [3] as [VARCHAR] - [<Token too long to write in question>] //Actual data type is LONGTEXT
binding parameter [4] as [BIGINT] - [null] //this is a problem (user_id should not be - should be a long numebr such as: 5531405900210671089)
binding parameter [5] as [BIGINT] - [0] //this is a problem (token_id should be a long number such as: -8824825685434914749)
SQL Error: 1048, SQLState: 23000
Column 'user_id' cannot be null

2 个答案:

答案 0 :(得分:2)

您不需要在令牌中使用@Id注释user_id:您看到这是有效的。 同样在数据库中,足以将表令牌的主键定义为tokednId。 当然,user_id必须设置为外键,不能为空。

答案 1 :(得分:1)

这是&#34;派生的身份&#34;,因此Token需要@IdClass,如下所示:

public class TokenId implements Serializable {
    private long tokenId; // matches the name of the attribute
    private long user;  // matches name of attribute and type of User PK
    ...
}

然后Token需要像这样指定@IdClass

@Entity
@IdClass(TokenId.class)
public class Token {
    ...
}

在第2.4.1节的JPA 2.1规范中讨论了衍生身份(带有示例)。