【发布时间】: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