gpt4 book ai didi

java - Hibernate:@ManyToOne,@OneToMany 在结果中给出空值

转载 作者:行者123 更新时间:2023-11-29 06:45:37 25 4
gpt4 key购买 nike

我有java应用程序(Spring + Hibernate)和mySql DB。
Spring :5.0.2
hibernate :5.2.12。

有两个实体“学生”和“类(class)”。它们之间的关系是:一名学生对应多节课(类(class)表中的外键)。
代码:

@Entity
@Table(name = "students")
@XmlRootElement
public class Student implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@Basic(optional = false)
@Column(name = "student_id")
private String studentId;

@OneToMany(cascade = CascadeType.ALL, mappedBy = "studentId")
private Collection<Lesson> lessonCollection;

// ...<other fields and some code>...
}

@Entity
@Table(name = "lessons")
@XmlRootElement
public class Lesson implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@Basic(optional = false)
@Column(name = "lesson_id")
private String lessonId;

@JoinColumn(name = "student_id", referencedColumnName = "student_id")
@ManyToOne(optional = false)
private Student studentId;

@Basic(optional = false)
@Column(name = "number")
private int number;

// ...<other fields and some code>...
}

在数据库中,学生和类(class)的所有字段均已填充。

我可以使用 Criteria API 成功选择所有学生。但是当我选择类(class)(一门/全部)时,我遇到了 Hibernate 异常:
org.hibernate.Property.AccessException:空值被分配给 org.Lesson.number 的原始类型 setter 的属性 [class org.Lesson.number]。

如果我将字段“number”更改为整数(可为空),那么我会得到这样的结果:
[空,空,空]
使用 HQL 发出请求会得到相同的结果。

有人可以给点建议吗?实体及其关系有什么问题?
提前致谢!

更新:
获取结果的代码:

public List<E> getAll() throws SQLException {
CriteriaBuilder builder = curSession().getCriteriaBuilder();
CriteriaQuery<? extends E> criteriaQuery = builder.createQuery(daoType);
criteriaQuery.from(daoType);
Query query = curSession().createQuery(criteriaQuery);
try {
System.out.println(query.getResultList());
} catch (Throwable e) {
throw new SQLException(e.getMessage()); // that's where it's fire
}
}

结果必须类似于
[org.Lesson[lessonId=1]、org.Lesson[lessonId=2]、org.Lesson[lessonId=3]]

UPD2:
异常(exception):

àïð 02, 2018 4:38:18 PM org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging org.apache.cxf.interceptor.Fault: Null value was assigned to a property [class org.Lesson.number] of primitive type setter of org.Lesson.number; nested exception is org.hibernate.PropertyAccessException: Null value was assigned to a property [class org.Lesson.number] of primitive type setter of org.Lesson.number at org.apache.cxf.service.invoker.AbstractInvoker.createFault(AbstractInvoker.java:162) at org.apache.cxf.jaxws.AbstractJAXWSMethodInvoker.createFault(AbstractJAXWSMethodInvoker.java:267) at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:128) at org.apache.cxf.jaxws.AbstractJAXWSMethodInvoker.invoke(AbstractJAXWSMethodInvoker.java:232) at org.apache.cxf.jaxws.JAXWSMethodInvoker.invoke(JAXWSMethodInvoker.java:85) at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:74) at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:59) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at org.apache.cxf.interceptor.ServiceInvokerInterceptor$2.run(ServiceInvokerInterceptor.java:126) at org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37) at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:131) at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:308) at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:121) at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:267) at org.apache.cxf.transport.servlet.ServletController.invokeDestination(ServletController.java:234) at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:208) at org.apache.cxf.transport.servlet.ServletController.invoke(ServletController.java:160) at org.apache.cxf.transport.servlet.CXFNonSpringServlet.invoke(CXFNonSpringServlet.java:191) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.handleRequest(AbstractHTTPServlet.java:301) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.doPost(AbstractHTTPServlet.java:220) at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) at org.apache.cxf.transport.servlet.AbstractHTTPServlet.service(AbstractHTTPServlet.java:276) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) Caused by: org.springframework.orm.hibernate5.HibernateSystemException: Null value was assigned to a property [class org.Lesson.number] of primitive type setter of org.Lesson.number; nested exception is org.hibernate.PropertyAccessException: Null value was assigned to a property [class org.Lesson.number] of primitive type setter of org.Lesson.number at org.springframework.orm.hibernate5.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:302) at org.springframework.orm.hibernate5.HibernateExceptionTranslator.convertHibernateAccessException(HibernateExceptionTranslator.java:70) at org.springframework.orm.hibernate5.HibernateExceptionTranslator.translateExceptionIfPossible(HibernateExceptionTranslator.java:55) at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:153) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) at com.sun.proxy.$Proxy44.getAll(Unknown Source) at org.service.LessonServiceImpl.getAll(LessonServiceImpl.java:64) 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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:338) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:294) at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:98) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:185) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:212) at com.sun.proxy.$Proxy45.getAll(Unknown Source) at org.src.LessonWorkerImpl.getTasks(LessonWorkerImpl.java:155) 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.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:179) at org.apache.cxf.jaxws.JAXWSMethodInvoker.performInvocation(JAXWSMethodInvoker.java:66) at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96) ... 36 more Caused by: org.hibernate.PropertyAccessException: Null value was assigned to a property [class org.Lesson.number] of primitive type setter of org.Lesson.number at org.hibernate.property.access.spi.SetterFieldImpl.set(SetterFieldImpl.java:47) at org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:709) at org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:205) at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:4707) at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:183) at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:125) at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1152) at org.hibernate.loader.Loader.processResultSet(Loader.java:1011) at org.hibernate.loader.Loader.doQuery(Loader.java:949) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341) at org.hibernate.loader.Loader.doList(Loader.java:2692) at org.hibernate.loader.Loader.doList(Loader.java:2675) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2507) at org.hibernate.loader.Loader.list(Loader.java:2502) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:502) at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:384) at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216) at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1490) at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1445) at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1414) at org.hibernate.query.Query.getResultList(Query.java:146) at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:72) at org.dao.GenericDaoImpl.getAll(GenericDaoImpl.java:90) 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.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:338) at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:197) at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:163) at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:139) ... 60 more Caused by: java.lang.IllegalArgumentException: Can not set int field org.kvant.suz.utils.data.db.domain.Task.executingStatus to null value at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) at sun.reflect.UnsafeIntegerFieldAccessorImpl.set(UnsafeIntegerFieldAccessorImpl.java:80) at java.lang.reflect.Field.set(Field.java:764) at org.hibernate.property.access.spi.SetterFieldImpl.set(SetterFieldImpl.java:41) ... 90 more

最佳答案

默认情况下 @OneToMany FetchTypeLazy 。这样就不会被加载了。如下所示更改您的映射。注意:FetchType 指定为 Eager

@OneToMany(cascade = CascadeType.ALL, mappedBy = "studentId",fetch=FetchType.LAZY)
private Collection<Lesson> lessonCollection;

getLessonCollection 将返回代理对象,该对象将具有实际对象的加载数据。

关于java - Hibernate:@ManyToOne,@OneToMany 在结果中给出空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49611577/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com