当前位置: 首页 > 知识库问答 >
问题:

Hibernate ElementCollection(fetch=FetchType.EAGER)导致PropertyAccessException

林鹭洋
2023-03-14

我使用spring-boot-1.5.3和spring数据jpa,有两个实体,都在cloumn标签和昵称上有jpa注释,Hibernate将根据实体自动生成表。请参见作业。javatable的默认集合table是主键job\u id,但我更改为job\u name,集合标签可以为空。此时会发生异常

名为Job2的作业没有任何标签,这意味着Settags是empty.when我使用jobDao.findOne(3);要获取Job2,Hibernate抛出异常org.hibernate.property.access.spi.Property tyAccessException原因:java.lang.IllegalArgumentException:无法设置java.lang.字符串字段hello.entity.Job.namejava.lang.整数

当我将@ElementCollection(fetch=FetchType.EAGER)更改为@ElementCollection(fetch=FetchType.LAZY)时,一切都很顺利。但我不知道为什么FetchType。当一个实体的集合列中没有元素时,EAGER将导致异常。而且,即使hibernate应该知道使用名称而不是id,它仍然会尝试转换作业。作业名称。id full stacktrace是

org.springframework.orm.jpa.JpaSystemException: Error accessing field [private java.lang.String hello.entity.Job.name] by reflection for persistent property [hello.entity.Job#name] : 3; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.String hello.entity.Job.name] by reflection for persistent property [hello.entity.Job#name] : 3
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:333)
    at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:488)
    at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
    at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.repository.core.support.SurroundingTransactionDetectorMethodInterceptor.invoke(SurroundingTransactionDetectorMethodInterceptor.java:57)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
    at com.sun.proxy.$Proxy115.findOne(Unknown Source)
    at hello.ApplicationTests.testJob2(ApplicationTests.java:67)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.String hello.entity.Job.name] by reflection for persistent property [hello.entity.Job#name] : 3
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:43)
    at org.hibernate.tuple.component.AbstractComponentTuplizer.getPropertyValue(AbstractComponentTuplizer.java:58)
    at org.hibernate.type.ComponentType.getPropertyValue(ComponentType.java:419)
    at org.hibernate.type.ComponentType.getHashCode(ComponentType.java:242)
    at org.hibernate.engine.spi.CollectionKey.generateHashCode(CollectionKey.java:64)
    at org.hibernate.engine.spi.CollectionKey.<init>(CollectionKey.java:58)
    at org.hibernate.engine.spi.CollectionKey.<init>(CollectionKey.java:43)
    at org.hibernate.engine.loading.internal.CollectionLoadContext.getLoadingCollection(CollectionLoadContext.java:95)
    at org.hibernate.loader.plan.exec.process.internal.CollectionReferenceInitializerImpl.finishUpRow(CollectionReferenceInitializerImpl.java:105)
    at org.hibernate.loader.plan.exec.process.internal.AbstractRowReader.readRow(AbstractRowReader.java:121)
    at org.hibernate.loader.plan.exec.internal.EntityLoadQueryDetails$EntityLoaderRowReader.readRow(EntityLoadQueryDetails.java:239)
    at org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorImpl.extractResults(ResultSetProcessorImpl.java:122)
    at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:122)
    at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:86)
    at org.hibernate.loader.entity.plan.AbstractLoadPlanBasedEntityLoader.load(AbstractLoadPlanBasedEntityLoader.java:167)
    at org.hibernate.persister.entity.AbstractEntityPersister.load(AbstractEntityPersister.java:4019)
    at org.hibernate.event.internal.DefaultLoadEventListener.loadFromDatasource(DefaultLoadEventListener.java:508)
    at org.hibernate.event.internal.DefaultLoadEventListener.doLoad(DefaultLoadEventListener.java:478)
    at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:219)
    at org.hibernate.event.internal.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:278)
    at org.hibernate.event.internal.DefaultLoadEventListener.doOnLoad(DefaultLoadEventListener.java:121)
    at org.hibernate.event.internal.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:89)
    at org.hibernate.internal.SessionImpl.fireLoad(SessionImpl.java:1129)
    at org.hibernate.internal.SessionImpl.access$2600(SessionImpl.java:164)
    at org.hibernate.internal.SessionImpl$IdentifierLoadAccessImpl.load(SessionImpl.java:2696)
    at org.hibernate.internal.SessionImpl.get(SessionImpl.java:975)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1075)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.find(AbstractEntityManagerImpl.java:1039)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:298)
    at com.sun.proxy.$Proxy101.find(Unknown Source)
    at org.springframework.data.jpa.repository.support.SimpleJpaRepository.findOne(SimpleJpaRepository.java:241)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:504)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:489)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:461)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    ... 39 more
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.String field hello.entity.Job.name to java.lang.Integer
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
    at java.lang.reflect.Field.get(Field.java:393)
    at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:39)
    ... 88 more



mysql> select * from employee;
+----+------+
| id | name |
+----+------+
|  2 | E1   |
|  3 | E2   |
+----+------+
2 rows in set

mysql> select * from employee_nick_names;
+-------------+------------+
| employee_id | nick_names |
+-------------+------------+
|           2 | E1A        |
|           2 | E1B        |
+-------------+------------+
2 rows in set

mysql> select * from job;
+----+------+
| id | name |
+----+------+
|  2 | Job1 |
|  3 | Job2 |
+----+------+
2 rows in set

mysql> select * from job_tags;
+----------+---------+
| job_name | job_tag |
+----------+---------+
| Job1     | Tag1    |
| Job1     | Tag2    |
+----------+---------+
2 rows in set

工作Java语言

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Job implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Integer id;
    private String name;

    @ElementCollection(fetch=FetchType.EAGER)
//  @ElementCollection(fetch = FetchType.LAZY)
    @CollectionTable(name = "job_tags", joinColumns = @JoinColumn(name = "job_name", referencedColumnName = "name"))
    @Column(name = "job_tag")
    private Set<String> tags = new HashSet<String>();
}

受雇者Java语言

@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee implements Serializable {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue
    private Integer id;
    private String name;

    @ElementCollection(fetch=FetchType.EAGER)
//  @ElementCollection(fetch = FetchType.LAZY)
    private Set<String> nickNames = new HashSet<String>();
}

JobDao。Java语言

public interface JobDao extends JpaRepository<Job, Integer> {}

雇员道。Java语言

public interface EmployeeDao extends JpaRepository<Employee, Integer> {}

应用定位测试。Java语言

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {

    @Autowired
    JobDao jobDao;
    @Autowired
    EmployeeDao employeeDao;

    @Test
    public void testEmployee() {
        employeeDao.findAll().forEach(e -> employeeDao.delete(e));

        Employee e1 = new Employee();
        e1.setName("E1");
        e1.setNickNames(Sets.newSet("E1A", "E1B"));
        employeeDao.save(e1);

        Employee e2 = new Employee();
        e2.setName("E2");
        employeeDao.save(e2);
    }

    @Test
    @Transactional
    public void testEmployee2() {
        Employee employee1 = employeeDao.findOne(2);
        System.out.println(employee2);
        Employee employee2 = employeeDao.findOne(3);
        System.out.println(employee3);
    }

    @Test
    public void testJob() {
        jobDao.findAll().forEach(e -> jobDao.delete(e));

        Job job1 = new Job();
        job1.setName("Job1");
        job1.setTags(Sets.newSet("Tag1", "Tag2"));
        jobDao.save(job1);

        Job job2 = new Job();
        job2.setName("Job2");
        jobDao.save(job2);
    }

    @Test
    @Transactional
    public void testJob2() {
        Job job1 = jobDao.findOne(2);
        System.out.println(job2);
        Job job2 = jobDao.findOne(3);
        System.out.println(job3);
    }
}

共有1个答案

慕朝明
2023-03-14

当你查询工作时

带着渴望

hibernate将立即获得“job\u标记”

并获取名称字段的值,

但是名称字段是私有的==

懒惰

Hibernate获取作业表单数据库(不获取“job\u标记”)

当您隐式调用getJobTags时,job_tags将被加载

 类似资料:
  • 问题内容: 在大型应用程序中,我与EAGER的关系存在问题。此应用程序中的某些实体与其他实体具有关联。这在某些功能上成为“毒药”。 现在,我的团队需要优化此功能,但是 我们无法将访存类型更改为LAZY ,因为我们需要重构整个应用程序。 所以,我的问题是:是否有一种方法可以执行特定的查询而忽略我返回的实体中的EAGER关联? 示例:当我有这个实体Person时,我在查询以查找Person时不带地址列

  • 问题内容: 我注意到执行和启动任务有时会抛出EXC_BAD_ACCESS。给出错误的实际调用方法似乎有所不同,但始终来自。在大多数情况下,调用方法来自。我在下面附加了两个崩溃日志,其中包含不同的调用方。我还附加了的实现。 不幸的是,我无法可靠地重现该错误,因此没有共享的示例脚本。创建和启动对象最终将产生错误。较大的文件似乎更经常发生。我在这里实施错了吗?有没有一种好的方法可以从此堆栈跟踪进行调试?

  • 问题内容: Javascript上找到的脚本是:如何获取在中断标签之后/之前的文本节点,并用ddb标签包装它们? 在通过WebDriver加载的每个页面上运行时, 测试运行3分钟后出现以下错误: 基本上,其目的是捕获xpath语法无法选择的文本节点。Javascript在带有break的break标签之前和之后包装文本节点。然后,WebDriver可以使用xpath语法获取文本。 事情似乎运行顺利

  • 我有点进退两难。我无法调试我的C OpenGL程序,因为激活调试消息会导致segfault。 我注册了一个调试回调函数: 我在以下代码中启动调试上下文: 如果我只是注释掉

  • Attribute Name Type Required Default Description file string Yes n/a the file, http or ftp site to fetch assign string No n/a the template variable the output will be assigned to 属性 类型 是否必须 缺省值 描述 fil

  • 执行pull,远程数据库的内容就会自动合并。但是,有时只是想确认本地数据库的内容而不想合并。这种情况下,请使用fetch。 执行fetch就可以取得远程数据库的最新历史记录。取得的提交会导入到没有名字的分支,这个分支可以从名为FETCH_HEAD的退出。 例如,在本地数据库和远程数据库的origin,如果在从B进行提交的状态下执行fetch,就会形成如下图所示的历史记录。 在这个状态下,若要把远程