2015-05-03 2 views
1

Я получаю много ошибок, которые, честно говоря, я не понимаю. Сначала я использовал JHipster для создания этого приложения. Очень полезная часть технологии open source, но она делает несколько вещей, с которыми я не знаком.Без свойства getMaterials найдено для типа Материал! и Ошибка создания bean с именем «materialRepository»:

Я просто пытаюсь вставить значения в базу данных через JPA.

/** 
* Spring Data JPA repository for the Material entity. 
*/ 
public interface MaterialRepository extends JpaRepository<Material,Long> { 

    public void uploadMaterialData(String material_number, BigDecimal material_thickness,String material_size,BigDecimal lb_per_sheet,BigDecimal dollar_per_lb); 

    List<Material> getMaterials(BigDecimal material_number); 

} 

маленький кусочек MaterialResource.java однако он имеет .save

if (cit.hasNext()) { 
       cell = cit.next(); 
       cell.setCellType(Cell.CELL_TYPE_STRING); 
       String dollar_per_lb = cell.getStringCellValue(); 
       Double perLb_as_double = Double.parseDouble(dollar_per_lb); 
       //now the conversion into big decimal happens 
       BigDecimal dollar_per_lb_as_BigDecimal = new 
       BigDecimal(perLb_as_double,MathContext.DECIMAL64); 
       this.dollar_per_lb = dollar_per_lb_as_BigDecimal; 
       material.setDollar_per_lb(dollar_per_lb_as_BigDecimal); 
      } 

      Long materialValue = 
      Long.parseLong(material.getMaterial_number()); 

      //puts materials into map and the key is the material number 
      materialMap.put(materialValue, material); 

      materialRepository.save(material); 
     } 

     workbook.close(); 

Material.java

public class Material implements Serializable { 

/** 
* 
*/ 
private static final long serialVersionUID = 1L; 

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 

private Long id; 

@Column(name = "material_number") 
private String material_number; 

@Column(name = "material_thickness", precision=10, scale=2) 
private BigDecimal material_thickness; 

@Column(name = "material_size") 
private String material_size; 

@Column(name = "lb_per_sheet", precision=10, scale=2) 
private BigDecimal lb_per_sheet; 

@Column(name = "dollar_per_lb", precision=10, scale=2) 
private BigDecimal dollar_per_lb; 

@Column(name = "inventory_count") 
private Integer inventory_count; 

....getter and setter methods below 

ApplicationWebXml.java

/** 
* This is a helper Java class that provides an alternative to creating a 
web.xml. 
*/ 
public class ApplicationWebXml extends SpringBootServletInitializer { 

private final Logger log = LoggerFactory.getLogger(ApplicationWebXml.class); 

@Override 
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 
    return application.profiles(addDefaultProfile()) 
      .showBanner(false) 
      .sources(Application.class); 
} 

/** 
* Set a default profile if it has not been set. 
* <p/> 
* <p> 
* Please use -Dspring.profiles.active=dev 
* </p> 
*/ 
private String addDefaultProfile() { 
    String profile = System.getProperty("spring.profiles.active"); 
    if (profile != null) { 
     log.info("Running with Spring profile(s) : {}", profile); 
     return profile; 
    } 

    log.warn("No Spring profile configured, running with default  
configuration"); 
    return Constants.SPRING_PROFILE_DEVELOPMENT; 
} 
} 

Appli cation.java

@ComponentScan @EnableAutoConfiguration (исключить = {MetricFilterAutoConfiguration.class, MetricRepositoryAutoConfiguration.class}) общественного класса Применение {

private static final Logger log = LoggerFactory.getLogger(Application.class); 

@Inject 
private Environment env; 

/** 
* Initializes hillcrestToolDie. 
* <p/> 
* Spring profiles can be configured with a program arguments --spring.profiles.active=your-active-profile 
* <p/> 
*/ 
@PostConstruct 
public void initApplication() throws IOException { 
    if (env.getActiveProfiles().length == 0) { 
     log.warn("No Spring profile configured, running with default configuration"); 
    } else { 
     log.info("Running with Spring profile(s) : {}", Arrays.toString(env.getActiveProfiles())); 
    } 
} 

    /** 
    * Main method, used to run the application. 
    */ 
    public static void main(String[] args) throws UnknownHostException { 
     SpringApplication app = new SpringApplication(Application.class); 
     app.setShowBanner(false); 

     SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); 

     // Check if the selected profile has been set as argument. 
     // if not the development profile will be added 
     addDefaultProfile(app, source); 
     addLiquibaseScanPackages(); 
     Environment env = app.run(args).getEnvironment(); 
     log.info("Access URLs:\n----------------------------------------------------------\n\t" + 
      "Local: \t\thttp://127.0.0.1:{}\n\t" + 
      "External: \thttp://{}:{}\n----------------------------------------------------------", 
      env.getProperty("server.port"), 
      InetAddress.getLocalHost().getHostAddress(), 
      env.getProperty("server.port")); 

    } 

    /** 
    * Set a default profile if it has not been set 
    */ 
    private static void addDefaultProfile(SpringApplication app, SimpleCommandLinePropertySource source) { 
     if (!source.containsProperty("spring.profiles.active")) { 
      app.setAdditionalProfiles(Constants.SPRING_PROFILE_DEVELOPMENT); 
     } 
    } 

    /** 
    * Set the liquibases.scan.packages to avoid an exception from ServiceLocator. 
    */ 
    private static void addLiquibaseScanPackages() { 
     System.setProperty("liquibase.scan.packages", Joiner.on(",").join(
      "liquibase.change", "liquibase.database", "liquibase.parser", 
      "liquibase.precondition", "liquibase.datatype", 
      "liquibase.serializer", "liquibase.sqlgenerator", "liquibase.executor", 
      "liquibase.snapshot", "liquibase.logging", "liquibase.diff", 
      "liquibase.structure", "liquibase.structurecompare", "liquibase.lockservice", 
      "liquibase.ext", "liquibase.changelog")); 
    } 
} 

Ошибки:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'materialResource': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.htd.repository.MaterialRepository com.htd.web.rest.MaterialResource.materialRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'materialRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property getMaterials found for type Material! 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) 
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) 
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) 
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) 
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:686) 
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:320) 
    at com.htd.Application.main(Application.java:59) 
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.htd.repository.MaterialRepository com.htd.web.rest.MaterialResource.materialRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'materialRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property getMaterials found for type Material! 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) 
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) 
    ... 14 more 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'materialRepository': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property getMaterials found for type Material! 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) 
    ... 16 more 
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property getMaterials found for type Material! 
    at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:75) 
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:327) 
    at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:307) 
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:270) 
    at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:241) 
    at org.springframework.data.repository.query.parser.Part.<init>(Part.java:76) 
    at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:235) 
    at org.springframework.data.repository.query.parser.PartTree$Predicate.buildTree(PartTree.java:373) 
    at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:353) 
    at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:84) 
    at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:61) 
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:94) 
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:205) 
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:72) 
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:349) 
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:187) 
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:239) 
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:225) 
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570) 
    ... 26 more 
+0

Я полагаю, вы не использовали autowire Material bean в вашей конфигурации xml –

+1

Что сумасшедшая вещь, в этом созданном JHipster приложении нет файла configuration.xml. – Drew1208

ответ

1

Пружина данных держит механизм, с помощью которого запрос разрешается на основе имени метода, от docs

Механизм построения запросов, встроенный в хранилище данных Spring Data , полезен для создания сдерживающих запросов по объектам репозитория. Механизм полоса префиксов найти ... К, чтения ... Автор, запросы ... К, посчитай ... By и получить ...

так, когда get удаляются из вашего List<Material> getMaterials(BigDecimal material_number); он пытается на поиск свойства с именем materials против Material объект.

Как представляется, вы не хотите автоматически разрешать запрос для этого конкретного метода, поэтому вы можете просто изменить имя, чтобы механизм вывода запроса не выполнялся, например. List<Material> retrieveMaterials(BigDecimal material_number);

+0

можем ли мы пообщаться? Я довольно уверен, читая ваше сообщение, вы можете решить мою проблему, и я не хочу, чтобы куча пробелов в комментариях к этому сообщению. – Drew1208

+0

мы можем попробовать, но у меня есть только несколько минут –

+0

Я никогда не использовал чат здесь, я это выясню. Мой вопрос: как насчет 'void uploadMaterialData' Я использовал аннотацию' @ Query', и это тоже не сработало. Я прочитал один и тот же документ, который вы отправили, но кажется, что я просто продолжаю ударять по стенам. – Drew1208

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

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