>我有一个懒惰的一对一关系,我想每次使用加载它(同一模型有更多的一对一关系,我想对数据库进行更少的查询。
查看日志文件中的本机数据库查询,我可以看到当我不尝试访问时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)
进行测试时,一切正常..
非常感谢您的帮助。
我不会做一对一。
。在城市级:
@ManyToOne state;
(我通常对一方做 EAGER ,对另一方懒惰; (FetchType.EAGER, CascadeType.ALL, mappedBy='city')
(
。在状态类中:
@OneToMany city;
(一个州有许多城市(。
您确定日志中的某个地方有一个 INSERT 语句,该语句添加了具有正确 id 的正确城市?
如果不看到所有代码,很难知道。