我正在尝试将此模型保存到数据库中,然后检索我刚刚保存的内容。除了数据库生成的 UUID 字段外,每个字段都被检索。
@Entity
@Table(name = "usertoken")
public class UserToken implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "token", insertable = false, updatable = false, nullable = false)
private UUID token;
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name="usersid", nullable=false)
private User user;
@Column(name = "expiration", updatable = false, nullable = false)
private LocalDateTime expiration;
我从服务中保存 token token = tokenRepository.save(token);
生成此 SQLHibernate:
insert
into
usertoken
(expiration, usersid)
values
(?, ?)
下一条语句获取 token token = tokenRepository.findByUser(user);
我看到 SQL 选择包含 token 字段Hibernate:
select
usertoken0_.id as id1_8_,
usertoken0_.expiration as expirati2_8_,
usertoken0_.token as token3_8_,
usertoken0_.usersid as usersid4_8_
from
usertoken usertoken0_
where
usertoken0_.usersid=?
...但返回的对象的每个字段都填充了 token 。数据库在 token 列中有一个值。我不知道为什么它会填充除一个之外的每个领域。
这是有问题的表格:
CREATE TABLE public.usertoken
(
id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
usersid integer NOT NULL,
token uuid NOT NULL DEFAULT uuid_generate_v1(),
expiration timestamp without time zone NOT NULL,
CONSTRAINT "usertoken_pkey" PRIMARY KEY (id)
)
我忘了补充一点,当我稍后查询时,找到了 token 并且正确填充了 UUID 字段。那么 JPA 缓存有什么奇怪的吗?插入后 hibernate 是否会忽略数据库 DEFAULT 列值?tokenRepository.findByToken(UUID.fromString(userToken));
Hibernate:
select
usertoken0_.id as id1_8_,
usertoken0_.expiration as expirati2_8_,
usertoken0_.token as token3_8_,
usertoken0_.usersid as usersid4_8_
from
usertoken usertoken0_
where
usertoken0_.token=?
最佳答案
@org.hibernate.annotations.Generated(value = GenerationTime.INSERT)
@Column(name = "token", insertable = false,
updatable = false, nullable = false)
private UUID token;
select
仅针对 insert
之后的那一列关于spring - 保存后的 JPA 查询不返回数据库生成的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62941966/