0

我在同一张表中使用父子关系时遇到 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);
}

前 2 个测试通过。第 3 个总是在 hashcode 方法的第 2 行以 NullPointerException 失败。说名称为空。我验证这仅在设置 parentProductId 时发生。我不知道为什么会这样。名称永远不应为空。我为班级定义休眠注释的方式是否有错误?

如果有人感兴趣,这是我的堆栈跟踪......

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)

谢谢

4

1 回答 1

0

你有一个属性访问权限,让 Hibernate 使用 setter/getter 来管理对象。但是在您的 hashcode() 和 equals() 方法中,您直接使用绕过 Hibernate 的字段。

此外,如果您直接访问另一个类的 equals() 方法字段,如果该对象是代理,这将失败,因为它将尝试访问代理的字段,而真实对象本身是该代理的另一个字段。所以在这种情况下,你也应该使用 getter。

于 2012-10-24T20:43:45.920 回答