JPA, открыть JPA OneToMany - FailedObject - PullRequest
       80

JPA, открыть JPA OneToMany - FailedObject

0 голосов
/ 31 октября 2018

Я делаю простую концепцию OneToMany JPA и проверяю с помощью Junit. Ошибка FailedObject при получении сущности (отношение oneToMany) , я использую последнюю версию Oen JPA, TomEE 8.

Сообщение субъекта

import javax.persistence.*;
import java.util.List;

@Entity
public class Post {

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

    private String title;

    @OneToMany(mappedBy = "post", targetEntity = PostComments.class, cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private List<PostComments> postCommentsList;

  //Getter & Setter
}

PostComments

import javax.persistence.*;

@Entity
public class PostComments {

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

    @ManyToOne
    @JoinColumn(name = "post_id", nullable = false)
    private Post post;

    private String review;

    //Getter & Setter
}

Услуги

@Stateless
public class PostService {

    @PersistenceContext(unitName = "movie-unit", type = PersistenceContextType.TRANSACTION)
    private EntityManager em;


    public void addPost() {
        PostComments postComments = new PostComments();
        postComments.setReview("Success Review");

        Post post = new Post();
        post.setTitle(" Welcome");
        postComments.setPost(post);
        List<PostComments> postCommentsList = new ArrayList<>();
        postCommentsList.add(postComments);
        post.setPostCommentsList(postCommentsList);

        em.persist(post);

        System.out.println(" Post has been saved .........");
    }

    public List<Post> getPost() {
        System.out.println("###########"+em);
        int id = 1;
        Post post = em.find(Post.class, id);
        return Arrays.asList(post);
        //return em.createQuery("select e from Post as e").getResultList();
    }


}

посттестовый

public class PostTest extends TestCase {

    @EJB
    private PostService postService;

    protected void setUp() throws Exception {
        final Map p = new Properties();
        p.put("movieDatabase", "new://Resource?type=DataSource");
        p.put("movieDatabase.JdbcDriver", "org.hsqldb.jdbcDriver");
        p.put("movieDatabase.JdbcUrl", "jdbc:hsqldb:mem:moviedb");
        EJBContainer.createEJBContainer(p).getContext().bind("inject", this);
    }

    @Test
    public void testPost() {
        postService.addPost();
        List<Post> postList = postService.getPost();
        System.out.println(" postList = "+postList);
        assertEquals(1,postList.size());
        System.out.println(postList.get(0).getTitle()+" "+postList.get(0).getPostCommentsList().get(0).getReview());
    }



}

JPA-запрос

INSERT INTO Post (id, title) VALUES (?,?) [Params = (int) 1, (String) Добро пожаловать]

PostComments (id, review, post_id) ЗНАЧЕНИЯ (?,?,?) [params = (int) 51, (String) Обзор успеха, (int) 1]

ВЫБРАТЬ t0.title, t1.post_id, t1.id, t1.review ОТ сообщения t0 ВЛЕВО ВНЕШНЕЕ СОЕДИНЕНИЕ PostComments t1 ON t0.id = t1.post_id ГДЕ t0.id =? ORDER BY t1.post_id ASC [params = (int) 1]

Исключение

SEVERE - EjbTransactionUtil.handleSystemException: null org.apache.openjpa.persistence.PersistenceException: null FailedObject: 1 [org.apache.openjpa.util.IntId] [java.lang.String] в org.apache.openjpa.kernel.BrokerImpl.find (BrokerImpl.java:1029) в org.apache.openjpa.kernel.BrokerImpl.find (BrokerImpl.java:923) в org.apache.openjpa.kernel.DelegatingBroker.find (DelegatingBroker.java:230) в org.apache.openjpa.persistence.EntityManagerImpl.find (EntityManagerImpl.java:495) в org.apache.openejb.persistence.JtaEntityManager.find (JtaEntityManager.java:224) на com.demo.ex.service.PostService.getPost (PostService.java:41) на sun.reflect.NativeMethodAccessorImpl.invoke0 (собственный метод) в sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) в sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) в java.lang.reflect.Method.invoke (Method.java:498) в org.apache.openejb.core.interceptor.ReflectionInvocationContext $ Invocation.invoke (ReflectionInvocationContext.java:205) в org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed (ReflectionInvocationContext.java:186) в org.apache.openejb.monitoring.StatsInterceptor.record (StatsInterceptor.java:191) в org.apache.openejb.monitoring.StatsInterceptor.invoke (StatsInterceptor.java:102) в sun.reflect.NativeMethodAccessorImpl.invoke0 (собственный метод) в sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) в sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) в java.lang.reflect.Method.invoke (Method.java:498) в org.apache.openejb.core.interceptor.ReflectionInvocationContext $ Invocation.invoke (ReflectionInvocationContext.java:205) в org.apache.openejb.core.interceptor.ReflectionInvocationContext.proceed (ReflectionInvocationContext.java:186) в org.apache.openejb.core.interceptor.InterceptorStack.invoke (InterceptorStack.java:85) в org.apache.openejb.core.stateless.StatelessContainer._invoke (StatelessContainer.java:252) в org.apache.openejb.core.stateless.StatelessContainer.invoke (StatelessContainer.java:212) в org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod (EjbObjectProxyHandler.java:265) в org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod (EjbObjectProxyHandler.java:260) в org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke (EjbObjectProxyHandler.java:89) в org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke (BaseEjbProxyHandler.java:347) в com.demo.ex.service.PostService $$ LocalBeanProxy.getPost (COM / демо / бывший / сервис / PostService.java) на com.demo.ex.PostTest.testPost (PostTest.java:30) на sun.reflect.NativeMethodAccessorImpl.invoke0 (собственный метод) в sun.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) в sun.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)в java.lang.reflect.Method.invoke (Method.java:498) в junit.framework.TestCase.runTest (TestCase.java:176) в junit.framework.TestCase.runBare (TestCase.java:141) в junit.framework.TestResult $ 1.protect (TestResult.java:122) в junit.framework.TestResult.runProtected (TestResult.java:142) в junit.framework.TestResult.run (TestResult.java:125) в junit.framework.TestCase.run (TestCase.java:129) в junit.framework.TestSuite.runTest (TestSuite.java:252) в junit.framework.TestSuite.run (TestSuite.java:247) в org.junit.internal.runners.JUnit38ClassRunner.run (JUnit38ClassRunner.java:86) в org.junit.runner.JUnitCore.run (JUnitCore.java:137) в com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs (JUnit4IdeaTestRunner.java:68) в com.intellij.rt.execution.junit.IdeaTestRunner $ Repeater.startRunnerWithArgs (IdeaTestRunner.java:47) в com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart (JUnitStarter.java:242) в com.intellij.rt.execution.junit.JUnitStarter.main (JUnitStarter.java:70) Вызывается: java.lang.NullPointerException at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.setInverseRelation (JDBCStoreManager.java:452) в org.apache.openjpa.jdbc.kernel.JDBCStoreManager.initializeState (JDBCStoreManager.java:412) в org.apache.openjpa.jdbc.kernel.JDBCStoreManager.initialize (JDBCStoreManager.java:305) в org.apache.openjpa.kernel.DelegatingStoreManager.initialize (DelegatingStoreManager.java:112) в org.apache.openjpa.kernel.ROPStoreManager.initialize (ROPStoreManager.java:57) в org.apache.openjpa.kernel.BrokerImpl.initialize (BrokerImpl.java:1048) в org.apache.openjpa.kernel.BrokerImpl.find (BrokerImpl.java:1006) ... еще 46

javax.ejb.EJBException: бин обнаружил, что приложение отсутствует исключение; Вложенное исключение: org.apache.openjpa.persistence.PersistenceException: null FailedObject: 1 [org.apache.openjpa.util.IntId] [java.lang.String]

в org.apache.openejb.core.ivm.BaseEjbProxyHandler.convertException (BaseEjbProxyHandler.java:447) в org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke (BaseEjbProxyHandler.java:351) в com.demo.ex.service.PostService $$ LocalBeanProxy.getPost (COM / демо / бывший / сервис / PostService.java)

Dependency

<dependency>
    <groupId>org.apache.tomee</groupId>
    <artifactId>javaee-api</artifactId>
    <version>8.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.apache.tomee</groupId>
    <artifactId>openejb-core</artifactId>
    <version>8.0.0-M1</version>
    <scope>test</scope>
</dependency>

Ответы [ 2 ]

0 голосов
/ 05 ноября 2018

кажется, что вы не улучшали свои объекты до запуска кода, поэтому некоторые функции не полностью функциональны: http://openjpa.apache.org/enhancement-with-maven.html

в качестве альтернативы вы можете установить openejb-javaagent на тестовой JVM (через верные аргументы вы можете передать -javaagent: /path/to/openejb-javaagent.jar, как в http://tomee.apache.org/javaagent.html), что будет делать то же самое (инструментирование байт-кодом) ) но во время выполнения как в простом томе

примечание: рекомендуется увеличить время сборки, если вам не нужно переносить этот код между несколькими провайдерами

Ромны

0 голосов
/ 31 октября 2018

Я только что попробовал тот же код с провайдером Hibernate. это работает хорошо. тот же код не работает с Open JPA: (

persistence.xml

<provider>org.hibernate.ejb.HibernatePersistence</provider>

Dependency

<dependency>
    <groupId>org.apache.tomee</groupId>
    <artifactId>openejb-core-hibernate</artifactId>
    <version>8.0.0-SNAPSHOT</version>
    <type>pom</type>
    <scope>test</scope>
</dependency>
...