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);
}

前两个测试通过。第三行在哈希码方法的第二行上始终失败。说名称为null。我仅在设置父productiDID时才能验证这一点。我不知道为什么会发生这种情况。这个名称永远不应为无效。我在定义班级的冬眠注释的方式上有错误吗?

如果有人有兴趣,这是我的stacktrace ....

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)

谢谢

您有一个属性访问权限,让Hibernate使用Setter/Getters来管理对象。但是在您的hashcode()&amp;equals()方法您直接使用绕过休眠的字段。

此外那代理。因此,在这种情况下,您也应该使用Getter。

最新更新