gpt4 book ai didi

复合键中的 Hibernate @GeneratedValue

转载 作者:行者123 更新时间:2023-12-05 01:20:40 28 4
gpt4 key购买 nike

问题:

我想在 hibernate 中映射以下内容 enter image description here

我在实现用户表时得到的错误是:

无法通过 User.id 的反射 setter 设置字段值

我正在使用 MySql 并且字段 ID 是自动递增的

@Entity
@Table(name="users")
public class User implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private Integer id;

@Id
private String username;

//Other fields
public User()
{

}

public User(String username, String email, String firstName,
String lastName, String password, String authority,
boolean enabled, boolean reset, boolean deleted)
{
this.username = username;
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.authority = authority;
this.enabled = enabled;
this.reset = reset;
this.deleted = deleted;
}

public User(int id, String username, String email, String firstName,
String lastName, String password, String authority,
boolean enabled, boolean reset, boolean deleted)
{
this.id = id;
this.username = username;
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.authority = authority;
this.enabled = enabled;
this.reset = reset;
this.deleted = deleted;
}

public int getId()
{
return id;
}

public void setId(int id)
{
this.id = id;
}

问题是,在 hibernate 状态下,如果我想为一个实体使用两个主键,我必须使用注解@Embedded,但我不确定如何正确使用它

我可以在 id 上使用 @Transient 注释轻松解决问题,但这似乎不是正确的方法

你能帮我解决这个问题吗

更新

感谢@Prasanna,我创建了以下但仍然是相同的问题

public class UserPK implements Serializable 
{
/**
*
*/
private static final long serialVersionUID = 1L;


protected Integer id;
protected String username;

public UserPK()
{

}

public UserPK(Integer id, String username)
{
this.id = id;
this.username = username;
}

@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result
+ ((username == null) ? 0 : username.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;
UserPK other = (UserPK) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (username == null) {
if (other.username != null)
return false;
} else if (!username.equals(other.username))
return false;
return true;
}
}

注意:我还更新了我的用户类

@Entity
@IdClass(UserPK.class)
@Table(name="users")
public class User implements Serializable
{

最佳答案

根据 Hibernate 中的当前实现,不可能在复合键中使用 @GeneratedValue,请选择复合键或单个 @GeneratedValue id。

在 Hibernate 中报告了一个关于带有自动生成部分的复合 ID 的问题 - HHH-6044

关于复合键中的 Hibernate @GeneratedValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29694257/

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