我在同一个表中使用父子关系时Hibernate有问题。我可以做选择和插入,但我不能删除。我写了一个JUnit测试,看看发生了什么,发现了一些奇怪的行为。
以下是我定义表格的方法:
CREATE TABLE `product` (
`productId` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`parentProductId` bigint(20) NULL DEFAULT NULL,
PRIMARY KEY (`productId`),
CONSTRAINT `FK_PARENTPRODUCT` FOREIGN KEY (`parentProductId`) REFERENCES `product` (`productId`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
我的产品类看起来像:
@Entity
@Table(name = "product")
public class Product {
private Long productId;
private String name;
private Product parentProduct;
private Set<Product> children;
private List<CustomerProduct> productCustomers;
public Product() {
}
public Product(Long productId, String name) {
this.productId = productId;
this.name = name;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
@NotNull
@Size(min = 1, max = 50)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToOne
@JoinColumn(name = "parentProductId")
public Product getParentProduct() {
return parentProduct;
}
public void setParentProduct(Product parentProduct) {
this.parentProduct = parentProduct;
}
@OneToMany(mappedBy = "parentProduct", fetch = FetchType.EAGER)
public Set<Product> getChildren() {
return children;
}
public void setChildren(Set<Product> children) {
this.children = children;
}
@OneToMany(mappedBy = "product")
public List<CustomerProduct> getProductCustomers() {
return productCustomers;
}
public void setProductCustomers(List<CustomerProduct> productCustomers) {
this.productCustomers = productCustomers;
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Product other = (Product) obj;
if (this.productId != other.productId
&& (this.productId == null || !this.productId.equals(other.productId)))
return false;
if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name))
return false;
return true;
}
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + name.length();
hash = 31 * hash + (name == null ? 0 : name.hashCode());
return hash;
}
@Override
public String toString() {
return "Product [productId=" + productId + ", name=" + name + "]";
}
}
我写了几个JUnit测试:
@Test
@Transactional(readOnly=true)
public void getProductNoChildren() {
Product p = productService.getProductById(Long.parseLong("1"));
assertNotNull(p);
assertTrue(p.getName().equals("Test"));
assertNull(p.getParentProduct());
assertTrue(p.getChildren().size() == 0);
}
@Test
@Transactional(readOnly=true)
public void getProductWithChildren() {
Product p = productService.getProductById(Long.parseLong("10"));
assertNotNull(p);
assertTrue(p.getName().equals("Test_2"));
assertNull(p.getParentProduct());
assertTrue(p.getChildren().size() > 0);
}
@Test
@Transactional(readOnly=true)
public void getProductWithParent() {
Product p = productService.getProductById(Long.parseLong("20"));
assertNotNull(p);
assertTrue(p.getName().equals("Test_3"));
assertNotNull(p.getParentProduct());
assertTrue(p.getParentProduct().getProductId() == Long.parseLong("2"));
assertTrue(p.getChildren().size() == 0);
}
前两个测试通过。第3个总是在hashcode方法的第二行上出现NullPointerException失败。名称为null。我确认只有在设置了parentProductId时才会发生这种情况。我无法弄清楚为什么会这样。名称永远不应为null。我为我的类定义了hibernate注释的方式是否有错误?
如果有人有兴趣,这是我的堆栈跟踪.....
java.lang.NullPointerException
at com.symmetry.security.model.Product.hashCode(Product.java:145)
at java.util.HashMap.put(HashMap.java:372)
at java.util.HashSet.add(HashSet.java:200)
at java.util.AbstractCollection.addAll(AbstractCollection.java:305)
at org.hibernate.collection.PersistentSet.endRead(PersistentSet.java:352)
at org.hibernate.engine.loading.CollectionLoadContext.endLoadingCollection(CollectionLoadContext.java:261)
at org.hibernate.engine.loading.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:246)
at org.hibernate.engine.loading.CollectionLoadContext.endLoadingCollections(CollectionLoadContext.java:219)
at org.hibernate.loader.Loader.endCollectionLoad(Loader.java:1005)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:993)
at org.hibernate.loader.Loader.doQuery(Loader.java:857)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2037)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:76)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3293)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:496)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:477)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:285)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090)
at org.hibernate.impl.SessionImpl.internalLoad(SessionImpl.java:1038)
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:630)
at org.hibernate.type.EntityType.resolve(EntityType.java:438)
at org.hibernate.engine.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:139)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:982)
at org.hibernate.loader.Loader.doQuery(Loader.java:857)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2037)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:86)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:76)
at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:3293)
at org.hibernate.event.def.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:496)
at org.hibernate.event.def.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:477)
at org.hibernate.event.def.DefaultLoadEventListener.load(DefaultLoadEventListener.java:227)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:285)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:152)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:1090)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:1005)
at org.hibernate.impl.SessionImpl.get(SessionImpl.java:998)
at com.symmetry.security.dao.hibernate.HibernateAbstractDao.findById(HibernateAbstractDao.java:52)
at com.symmetry.security.dao.hibernate.HibernateAbstractDao$$FastClassByCGLIB$$b227fdff.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at com.symmetry.security.dao.hibernate.HibernateProductDao$$EnhancerByCGLIB$$415fcf17.findById(<generated>)
at com.symmetry.security.service.ProductServiceImpl.getProductById(ProductServiceImpl.java:42)
at com.symmetry.security.service.ProductServiceImpl$$FastClassByCGLIB$$8b8f4a88.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at com.symmetry.security.service.ProductServiceImpl$$EnhancerByCGLIB$$b032e753.getProductById(<generated>)
at com.symmetry.security.service.ProductServiceImplUnitTest.getProductWithParent(ProductServiceImplUnitTest.java:87)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
由于
答案 0 :(得分:0)
你有一个Property访问权限让Hibernate使用setter / getters来管理对象。但是在你的hashcode()&amp; equals()方法直接使用字段绕过Hibernate。
此外,如果您直接访问另一个类的equals()方法字段,如果该对象是代理,则会失败,因为它将尝试访问代理的字段,而真实对象本身是另一个字段那个代理人。所以在这种情况下你也应该使用getter。