这个问题与Hibernate Annotation Placement Question有些相关.
但我想知道哪个更好?通过属性访问或通过字段访问?各有哪些优缺点?
我目前正在学习Hibernate和Java Persistence API.
我有一个@Entity类,需要将注释应用于各个字段.我已经在下面的代码中包含了他们可以去的所有三个地方.
我应该将它们应用于场地本身,吸气剂还是定位器?这三个选项之间的语义差异(如果有的话)是什么.
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.Id;
@Entity
@Table(name = "song")
public class Song {
// Annotations should only be applied to one of the below
@Id
@Column(name="id", unique=true, nullable=false)
private int id;
@Id
@Column(name="id", unique=true, nullable=false)
public int getId() {
return id;
}
@Id
@Column(name="id", unique=true, nullable=false)
public void setId(int id) {
this.id = id;
}
}
Run Code Online (Sandbox Code Playgroud) 我有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.
我该如何调查这个问题?导致这种错误行为的可能原因是什么?