这是让我感到困惑的一个.我正在尝试实现一个基本的Hibernate DAO结构,但是遇到了问题.
这是基本代码:
int startingCount = sfdao.count();
sfdao.create( sf );
SecurityFiling sf2 = sfdao.read( sf.getId() );
sfdao.delete( sf );
int endingCount = sfdao.count();
assertTrue( startingCount == endingCount );
assertTrue( sf.getId().longValue() == sf2.getId().longValue() );
assertTrue( sf.getSfSubmissionType().equals( sf2.getSfSubmissionType() ) );
assertTrue( sf.getSfTransactionNumber().equals( sf2.getSfTransactionNumber() ) );
Run Code Online (Sandbox Code Playgroud)
它在第三个assertTrue上失败,它试图将sf中的值与sf2中的相应值进行比较.这是例外:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:86)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:140)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
at com.freightgate.domain.SecurityFiling_$$_javassist_7.getSfSubmissionType(SecurityFiling_$$_javassist_7.java)
at com.freightgate.dao.SecurityFilingTest.test(SecurityFilingTest.java:73)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:40)
Run Code Online (Sandbox Code Playgroud) 目前,Hibernate允许我直接加载由*-to-one关系定义的对象
entity1.getEntity2()
Run Code Online (Sandbox Code Playgroud)
是否可以获取外键而不是对象?
我看到的当前方法是对我的映射添加addint:
@JoinColumn(name="message_key")
@ManyToOne(targetEntity=Message.class,fetch=FetchType.LAZY)
private Message message; //these lines currently exist
@Column(name="message_key")
private Long message_fk; //the idea is to add those 2 lines
Run Code Online (Sandbox Code Playgroud)
是否有更好的方法来获取外键,或者这是唯一的?
当我们在Hibernate中保存一个对象时,我们将依赖对象保存为id而不是加载该对象并保存它.
例如:员工有一个部门外键,所以如果我们需要保存员工对象,那么我们将执行以下操作:
saveEmployee{
emp.setName(name);
Department department = session.find(Department.class,deptid);
emp.setDepartment(department);
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我们导入1000条记录,并且我们在excel中将deptid作为单独的列,那么将调用不必要的1000倍db来获取相应的部门.
有没有更好的方法 可以在没有对象到对象映射的情况下强制执行外键?