【问题标题】:Spring JPA LAZY load OneToOne relation won't loadSpring JPA LAZY load OneToOne 关系不会加载
【发布时间】:2017-05-08 20:19:07
【问题描述】:

我有一个 LAZY OneToOne 关系, 我想在每次使用时加载它(同一个模型有更多的 OneToOne 关系,我想对数据库做更少的查询。)

查看日志文件中的本机数据库查询,我可以看到当我不尝试访问 user.city 时,SELECT FROM City... 语句未打印。

但是当访问user.city 时,我可以看到日志中正在运行的 SQL 语句,我正在获取类实例。但City 实体中填充的所有内容均为null,更多信息见下文:

这段代码:

System.out.println(user.city);
System.out.println(user.city.location);

将打印

Hibernate: 
    select
        city0_.id as id1_3_0_,
        city0_.accentName as accentNa2_3_0_,
        city0_.location as location3_3_0_,
        city0_.name as name4_3_0_,
        city0_.state_id as state_id5_3_0_ 
    from
        City city0_ 
    where
        city0_.id=?
com.dateup.models.City@1ed01095
null

这就是我的模型:

@Entity
@Table(
    indexes={@Index(name = "name", columnList="name")}
)
public class City {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public Long id;

    @JsonIgnore
    @ManyToOne(fetch = FetchType.LAZY)
    public State state;

    public String name;
    public String accentName;

    @Column(name = "location", columnDefinition = "POINT")
    public Point location;
}

@Entity
@Table(
    name="User"
)
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorFormula("'User'")
@JsonAutoDetect 
public abstract class BaseUser { 
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public Long id;

    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    @OneToOne(fetch = FetchType.LAZY)
    public City city;

    ...
}

顺便提一下,当使用@OneToOne(fetch = FetchType.EAGER) 进行测试时,一切正常..

非常感谢您的帮助。

【问题讨论】:

  • 是否缺少 setter 或 @Entity(access = AccessType.FIELD) 有问题?
  • @maszter 我的字段是公开的,你是什么意思'r @Entity(access = AccessType.FIELD) 有问题?'

标签: java spring jpa one-to-one


【解决方案1】:

我不会一对一。

...在城市类中:

@ManyToOne state;(我通常是一方面渴望,另一方面懒惰;(FetchType.EAGER, CascadeType.ALL, mappedBy='city')

...在状态类中:

@OneToMany city;(一个州有很多城市)。

您确定您的日志中某处有一条 INSERT 语句,它添加了正确的城市和正确的 id 吗?

不看所有代码很难知道。

【讨论】:

  • 这里的城市类与用户没有关系。因为这个城市可以被很多用户使用
  • 另外我不知道为什么你有 User 作为一个抽象类?对吗?
  • 我以前有继承,所以 baseUser 留下来可能会再试一次...我有一个扩展 BaseUser 的 User 类,你认为这可以相关吗?
  • “JPA”没有理由需要二传手;设置FIELDS的多种方式
  • @NeilStockton 正确,我忘记了...还有 Shay,检查上面的编辑答案。如果不查看您是否在城市表中添加了某些内容,很难说出您的问题是什么。 EAGER 加载测试也是一个好主意。
猜你喜欢
  • 1970-01-01
  • 2014-12-14
  • 2019-08-12
  • 2021-05-22
  • 2023-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多