我有Hibernate Entities看起来像这样(getters和setter被遗漏):
@Entity
public class EntityA {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
private EntityB parent;
}
@Entity
public class EntityB extends SuperEntity {
@OneToMany(mappedBy = "parent")
@Fetch(FetchMode.SUBSELECT)
@JoinColumn(name = "parent_id")
private Set<EntityA> children;
}
@MappedSuperclass
public class SuperEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long itemId;
}
Run Code Online (Sandbox Code Playgroud)
当我查询EntityA时,它加载正常,父关联被Hibernate代理替换(因为它是Lazy).如果我想访问父母的id,我执行以下调用:
EntityA entityA = queryForEntityA();
long parentId = entityA.getParent().getItemId();
Run Code Online (Sandbox Code Playgroud)
据我所知,调用不应该向数据库进行往返,因为Id存储在EntityA表中,并且代理应该只返回该值.但是,在我的情况下,这将生成一个SQL语句,该语句提取EntityB,然后才返回Id.
我该如何调查这个问题?导致这种错误行为的可能原因是什么?
我试图坚持我的课程,但它总是引发我这个错误。
这是我的hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/Projecten2?zeroDateTimeBehavior=convertToNull</property>
<property name="hibernate.connection.username">MyUser</property>
<property name="hibernate.connection.password">MyPass</property>
<property name="hibernate.current_session_context_class">org.hibernate.context.ThreadLocalSessionContext</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<!-- Mappings -->
<mapping class="entity.Presentation"/>
</session-factory>
</hibernate-configuration>
Run Code Online (Sandbox Code Playgroud)
这是我要坚持的课程
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open …Run Code Online (Sandbox Code Playgroud)