2015-05-26 5 views
0

Я бы очень оценил, сможет ли кто-нибудь помочь в решении следующей проблемы.Данные Spring JPA для обработки сложного типа

Мой веб-сервис RESTful предоставляет ресурс сканирования без проблем. Однако, когда я пытаюсь добавить атрибут «attr1», как @ManyToMany для сканирования типа Collection

@ManyToMany 
Collection<AnotherType> attr1; 

Я получаю следующее сообщение об ошибке (после запуска МВЕН пружинных загрузок: бег):

орг .hibernate.MappingException: не удалось определить тип для: whatever.AnotherTypeSubOne, за столом: anothertype, для столбцов: [org.hibernate.mapping.Column (another_type_sub_one)]

, где anotherType является @Entity и имеет 3 атрибуты следующих типов:

  1. AnotherTypeSubOne,
  2. AnotherTypeSubTwo,
  3. Collection, как @ManyToMany (mappedBy = "attR1")

AnotherTypeSubOne и AnotherTypeSubTwo также @Entity и они содержат только атрибуты типа String. Атрибут thirs:

@ManyToMany(mappedBy = "attr1") 
Collection<Scan> scan; 

Что я делаю неправильно? Удастся ли мне заставить Spring автоматически обрабатывать JSON-представление сложной коллекции типов?

Большое вам спасибо!

Я хочу иметь GET/сканирование/возвращение представления JSON объекта сканирования, который включает в себя этот сложный атрибут attr1.

Для тех, кто предпочитает проходить через оригинальный код, вот он.

@Entity 
public class Scan { 

    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO) 
    private Long id; 


    private Long projectId; 

    @ManyToMany 
    private Collection<Result> result; 

<getter/setter methods> 

Результат Класс

@Entity 
public class Result { 

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
private Long id; 

private First vulnerability; 

private Second pathNode; 

@ManyToMany(mappedBy = "result") 
private Collection<Scan> scan; 

<getter/setter methods> 

Класс Первый

@Entity 
public class First { 

    @Id 
    private String id; 

    private String name; 

    private long score; 

    private String description; 

Класс Второй

@Entity 
public class Second { 

    @Id 
    private Long id; 

    private String name; 

    private int line; 

    private int col; 

    private String snippet; 

Класс ScanRepository

@RepositoryRestResource(collectionResourceRel = "scans", path = "scans") 
public interface ScanRepository extends PagingAndSortingRepository<Scan, Long> { 

    /** 
    * Custom query to retrieve a list of Scan objects based on their project's 
    * ID. 
    * 
    * @param pid project id 
    * @return 
    */ 
    List<Scan> findByProjectId(@Param("pid") String pid); 

Это все код (он полагается на встроенную базу данных H2). В pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 

    <groupId>com.waratek</groupId> 
    <artifactId>waratek-rasp</artifactId> 
    <version>1.0</version> 
    <packaging>war</packaging> 

    <name>waratek-rasp</name> 

    <properties> 
     <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir> 
     <!-- use UTF-8 for everything --> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
     <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> 
    </properties> 

    <dependencies> 
     <!-- Necessary in order to get rid of 
     java.lang.ClassFormatError: Absent Code attribute in method that is not 
     native or abstract in class file javax/faces/webapp/FacesServlet--> 
     <dependency> 
      <groupId>org.glassfish</groupId> 
      <artifactId>javax.faces</artifactId> 
      <version>2.1.6</version> 
     </dependency> 

     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-data-rest</artifactId> 
     </dependency> 
     <dependency> 
      <groupId>org.springframework.boot</groupId> 
      <artifactId>spring-boot-starter-data-jpa</artifactId> 
     </dependency> 
     <dependency> 
      <groupId>com.h2database</groupId> 
      <artifactId>h2</artifactId> 
     </dependency> 

     <dependency> 
      <groupId>org.springframework.hateoas</groupId> 
      <artifactId>spring-hateoas</artifactId> 
     </dependency> 

    </dependencies> 

    <build> 
     <plugins> 
      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-compiler-plugin</artifactId> 
       <version>2.3.2</version> 
       <configuration> 
        <source>1.6</source> 
        <target>1.6</target> 
        <compilerArguments> 
         <endorseddirs>${endorsed.dir}</endorseddirs> 
        </compilerArguments> 
       </configuration> 
      </plugin> 
      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-war-plugin</artifactId> 
       <version>2.1.1</version> 
       <configuration> 
        <failOnMissingWebXml>false</failOnMissingWebXml> 
       </configuration> 
      </plugin> 
      <plugin> 
       <groupId>org.springframework.boot</groupId> 
       <artifactId>spring-boot-maven-plugin</artifactId> 
      </plugin> 
      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-dependency-plugin</artifactId> 
       <version>2.1</version> 
       <executions> 
        <execution> 
         <phase>validate</phase> 
         <goals> 
          <goal>copy</goal> 
         </goals> 
         <configuration> 
          <outputDirectory>${endorsed.dir}</outputDirectory> 
          <silent>true</silent> 
          <artifactItems> 
           <artifactItem> 
            <groupId>javax</groupId> 
            <artifactId>javaee-endorsed-api</artifactId> 
            <version>6.0</version> 
            <type>jar</type> 
           </artifactItem> 
          </artifactItems> 
         </configuration> 
        </execution> 
       </executions> 
      </plugin> 
     </plugins> 
    </build> 




    <parent> 
     <groupId>org.springframework.boot</groupId> 
     <artifactId>spring-boot-starter-parent</artifactId> 
     <version>1.2.3.RELEASE</version> 
    </parent> 


    <repositories> 

     <!--  <repository> 
      <id>Java.Net</id> 
      <url>http://download.java.net/maven/2/</url> 
     </repository>--> 
     <!--  <repository> 
      <id>repository.jboss.org-public</id> 
      <name>JBoss repository</name> 
      <url>https://repository.jboss.org/nexus/content/groups/public</url> 
     </repository>--> 
     <repository> 
      <id>spring-releases</id> 
      <url>https://repo.spring.io/libs-release</url> 
     </repository> 



    </repositories> 
    <pluginRepositories> 
     <pluginRepository> 
      <id>spring-releases</id> 
      <url>https://repo.spring.io/libs-release</url> 
     </pluginRepository> 
    </pluginRepositories> 

</project> 
+1

Не описывайте свой код. Отправьте его. –

+0

@JBNizet добавил, спасибо – iammyr

ответ

1
private First vulnerability; 

private Second pathNode; 

должен быть

@ManyToOne 
private First vulnerability; 

@ManyToOne 
private Second pathNode; 

(или @OneToOne если уязвимость/pathNode принадлежит только один результат).

+0

большое вам спасибо, вы сделали мой день! – iammyr

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