2

Я использовал Neo4j 3.0.6, Neo4j-ОГМ 2.0.5, весна загрузки стартер 1.4.1 RELEASE, Lucene 5.5.2Spring Data Neo4j - Аргумент Тип Несовпадение

Это моя машина и machineSectionSummary класс (я только опубликуйте поле, на самом деле есть свойства и конструкторы). Когда я вызываю функцию updateMachineSectionSummary, после вызова этой функции и перезапуска программы, я не могу вызвать machineRepository.findByName и получить ошибку ниже. Как я могу это исправить? Я уже пытался удалить Дата, изменив имя отношения, но ее не работает

@NodeEntity 
public class Machine { 
@GraphId 
Long graphId; 
String id; 
private String name; 
private String field; 
private Date startDate; 
private Date endDate; 
@Relationship(type = "HAS_DEPTH_UNIT", direction = "OUTGOING") 
private Unit depthUnit; 
private Double duration; 
@Relationship(type = "HAS_DURATION_UNIT", direction = "OUTGOING") 
private Unit durationUnit; 
private Double cost; 
@Relationship(type = "HAS_CURRENCY", direction = "OUTGOING") 
private Currency currency; 
private Double exchangeRate; 
@Transient 
private Boolean maxCost; 
} 

@NodeEntity 
public class MachineSectionSummary { 
@GraphId 
Long graphId; 
String id; 
@Relationship(type = "HAS_MACHINE", direction = "OUTGOING") 
private Machine machine; 
private String sectionGroup; 
private String category; 
private Double duration; 
private Double percentDuration; 
private Double cost; 
private Double percentCost; 
@Relationship(type = "HAS_CURRENCY", direction = "OUTGOING") 
private Currency currency; 

}

В этой функции, когда я пытаюсь findById, его работа должным образом при первом запуске (после четкой базы данных и запустите программу), но после остановки и повторного запуска программы всегда ошибка.

public void updateMachineSectionSummary(String id) { 
    Machine currentMachine = findById(id); 
    if (currentMachine == null) { 
     return; 
    } 
    Engine currentEngine = engineService.findByMachineIdAndName(currentMachine.getId(), "Value"); 
    if (currentEngine == null) { 
     return; 
    } 
    List<LineItem> currentLineItemList = lineItemService.findByEngineIdAndActivityTypeOrderByNoAsc(currentEngine.getId(), "Inside"); 


    List<String> sectionGroupList = new ArrayList<String>(); 
    sectionGroupList.add("Section 1"); 
    sectionGroupList.add("Section 2"); 
    sectionGroupList.add("Section 3"); 
    sectionGroupList.add("Section 4"); 
    for (String sectionGroup : sectionGroupList) { 
     Double durationTotal = currentLineItemList.stream().filter(d -> d.getSection().getGroup().equalsIgnoreCase(sectionGroup)) 
       .mapToDouble(LineItem::getDuration).sum(); 
     durationTotal = durationTotal/24; 
     Double percentDurationTotal = (durationTotal/durationTotal) * 100.0; 

     MachineSectionSummary currentWSSTotal = machineSectionSummaryService.findByMachineNameAndSectionGroupAndCategory(currentMachine.getName(), 
       sectionGroup, "Total"); 
     if (currentWSSTotal != null) { 
      currentWSSTotal.setDuration(durationTotal); 
      currentWSSTotal.setPercentDuration(percentDurationTotal); 
      machineSectionSummaryService.save(currentWSSTotal); 
     } 
    } 
} 

Это ошибка журнала при запуске программы (второй раз)

java.lang.IllegalArgumentException: argument type mismatch 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_66] 
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_66] 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_66] 
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_66] 
at org.neo4j.ogm.entity.io.MethodWriter.write(MethodWriter.java:40) ~[neo4j-ogm-core-2.0.5.jar:na] 
at org.neo4j.ogm.entity.io.MethodWriter.write(MethodWriter.java:70) ~[neo4j-ogm-core-2.0.5.jar:na] 
at org.neo4j.ogm.context.GraphEntityMapper.writeProperty(GraphEntityMapper.java:234) ~[neo4j-ogm-core-2.0.5.jar:na] 
at org.neo4j.ogm.context.GraphEntityMapper.setProperties(GraphEntityMapper.java:186) ~[neo4j-ogm-core-2.0.5.jar:na] 
at org.neo4j.ogm.context.GraphEntityMapper.mapNodes(GraphEntityMapper.java:162) ~[neo4j-ogm-core-2.0.5.jar:na] 
at org.neo4j.ogm.context.GraphEntityMapper.mapEntities(GraphEntityMapper.java:145) ~[neo4j-ogm-core-2.0.5.jar:na] 
at org.neo4j.ogm.context.GraphEntityMapper.map(GraphEntityMapper.java:120) ~[neo4j-ogm-core-2.0.5.jar:na] 
at org.neo4j.ogm.context.GraphRowListModelMapper.map(GraphRowListModelMapper.java:56) ~[neo4j-ogm-core-2.0.5.jar:na] 
at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.loadAll(LoadByTypeDelegate.java:94) ~[neo4j-ogm-core-2.0.5.jar:na] 
at org.neo4j.ogm.session.delegates.LoadByTypeDelegate.loadAll(LoadByTypeDelegate.java:157) ~[neo4j-ogm-core-2.0.5.jar:na] 
at org.neo4j.ogm.session.Neo4jSession.loadAll(Neo4jSession.java:226) ~[neo4j-ogm-core-2.0.5.jar:na] 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_66] 
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_66] 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_66] 
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_66] 
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:133) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:121) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at com.sun.proxy.$Proxy77.loadAll(Unknown Source) ~[na:na] 
at org.springframework.data.neo4j.repository.query.derived.DerivedGraphRepositoryQuery.execute(DerivedGraphRepositoryQuery.java:65) ~[spring-data-neo4j-4.1.3.RELEASE.jar:na] 
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482) ~[spring-data-commons-1.12.3.RELEASE.jar:na] 
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460) ~[spring-data-commons-1.12.3.RELEASE.jar:na] 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61) ~[spring-data-commons-1.12.3.RELEASE.jar:na] 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) ~[spring-tx-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at com.sun.proxy.$Proxy116.findByName(Unknown Source) ~[na:na] 
at com.test.wp.service.MachineServiceImpl.findByName(MachineServiceImpl.java:58) ~[classes/:na] 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_66] 
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_66] 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_66] 
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_66] 
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) ~[spring-tx-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at com.sun.proxy.$Proxy121.findByName(Unknown Source) ~[na:na] 
at com.test.wp.service.InitializationServiceImpl.initGlobalOffsetMachines(InitializationServiceImpl.java:998) ~[classes/:na] 
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_66] 
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_66] 
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_66] 
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_66] 
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:333) ~[spring-aop-4.3.3.RELEASE.jar:4.3.3.RELEASE] 
at.. 

UPDATE

Я создаю sampleProject в Github. Надеюсь, что этот образец полезен. Спасибо

+0

Возможная ошибка. Можете ли вы отправить образец проекта, который я могу исследовать для вас? [email protected] –

+0

Можете ли вы также указать тип используемого драйвера? – digx1

+0

Хорошо, я собираюсь это сделать. Потому что он сложный, поэтому мне нужно разделить между важным кодом и нет. Подождите. Спасибо. –

ответ

3

Есть две части: первый касается вашего кода, а второй - то, что должен делать OGM, когда он сталкивается с этим сценарием.

MachineSectionSummary имеет поле под названием Double percentDuration. Когда вы инициализируете свою базу данных, он устанавливает каждый экземпляр в 0.0. При первом запуске /initMachineSectionSummary он называет updateMachineSectionSummary()

Линия, которая вводит проблему, находится здесь: Double percentDurationTotal = (durationTotal/durationTotal) * 100.0;. Выражение, которое создает durationTotal, всегда возвращает 0.0. Этот расчет приведет к NaN, который затем устанавливается на MachineSectionSummary.percentDuration. Затем OGM сохраняет это значение в Neo4j. Проблема возникает, когда вы обнаружили, когда пытаетесь получить значение NaN из базы данных и перенаправлять ее обратно на MachineSectionSummary. OGM на данный момент ожидает Double, но вместо этого получает строку «NaN», и она взрывается за исключением: java.lang.IllegalArgumentException: argument type mismatch.

Проработав над многими численными проектами, в прошлом моя рекомендация состояла в том, чтобы предотвратить появление NaN; то есть сделать защитную кодировку, где она потенциально может возникнуть. Это должно решить вашу основную проблему.

Это вводит второй вопрос: что мы ожидаем от OGM? В некоторых случаях некоторые пользователи могут захотеть сохранить NaN в базе данных. Некоторые пользователи могут захотеть удостовериться, что NaN всегда null. В любом случае OGM должен, вероятно, предупредить разработчиков с лучшим сообщением об ошибке.

+0

Это действительно то, что нам нужно знать, потому что нет ошибки, когда я пытаюсь сохранить его в базе данных, и без перезапуска программы он будет работать отлично, только получите возврат «NaN» или «NaN», бесконечность». Но на самом деле это неправильно в базе данных, потому что вернет неправильный аргумент. Просто предоставьте это с помощью условного IF ELSE. И это хорошо. большое спасибо –

 Смежные вопросы

  • Нет связанных вопросов^_^