gpt4 book ai didi

java - JPA 复合外主键

转载 作者:行者123 更新时间:2023-11-29 05:04:57 24 4
gpt4 key购买 nike

所以我目前有一个包含用户信息的数据库,定义用户的是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;
}
}

在这段代码片段之后,我得到了 token 的类

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 时,它就可以工作(即使在数据库中它是主键)。

任何帮助;

应用程序属性:

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

最佳答案

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

关于java - JPA 复合外主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50326307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com