JPA, открыть JPA OneToMany - FailedObject
Я делаю простую концепцию OneToMany JPA и проверяю с помощью Junit. Ошибка получения FailedObject при получении объекта (отношение oneToMany). Я использую последнюю версию Oen JPA, TomEE 8.
Post Entity
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 Query
INSERT INTO Post (id, title) VALUES (?,?) [Params = (int) 1, (String) Welcome]
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.kerlker. найти (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.PostServiceSPerviceService.Pet:41) в sun.reflect.NativeMethodAccessorImpl.invoke0(собственный метод) в sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) в sun.reflect.DelegatingMethodAccessorImplanj.jjjj. refle.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(StatsInteror19).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). apache.openejb.core.interceptor.ReflectionInvocationContext.proceed (ReflectionInvocationContext.java:186) в org.apache.openejb.core.interceptor.InterceptorStack.invoke(InterceptorStack.java:85) в org.apeta.opé.StatelessContainer._invoke(StatelessContainer.java:252) в org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:212) в org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbOb).apache.openejb.core.ivm..BaseEjbProxyHandler.invoke (BaseEjbProxyHandler.java:347) в com.demo.ex.service.PostService$$LocalBeanProxy.getPost(com/demo/ex/service/PostService.java) в com.demo.ex.PostTest.testPost(PostTest.java:30) в sun.reflect.NativeMethodAccessorImpl.invoke0(собственный метод) в sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) в sun.reflect.DelegatingMethodjor.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. запустить (TestResult.java:125) в junit.framework.TestCase.run(TestCase.java:129) в junit.framework.TestSuite.runTest(TestSuite.java:252) в junit.framework.TestSuite.run(TestSuite.java 247 JUnit4IdeaTestRunner.java:68) в com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47) в com.intellij.rt.execution.junit.Java.jnittart at com.intellij.rt.execution.junit.JUnitStarter.main (JUnitStarter.java:70) Причина: java.lang.NullPointerException в 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.initava5.apache.openjpa.kernel.DelegatingStoreManager.initialize(DelegatingStoreManager.java:112) в org.apache.openjpa.kernel.ROPStoreManager.initialize(ROPStoreManager.java:57) в org.apache.openjpa.kernelialI.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.mode:35).PostService $$ LocalBeanProxy.getPost (COM / демо / бывший / сервис / PostService.java)
зависимость
<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 ответа
Кажется, что вы не улучшали свои сущности до запуска кода, поэтому некоторые функции не полностью функциональны: http://openjpa.apache.org/enhancement-with-maven.html
в качестве альтернативы вы можете установить openejb-javaagent на тестовой JVM (через верные аргументы вы можете передать -javaagent:/path/to/openejb-javaagent.jar, как в http://tomee.apache.org/javaagent.html), что сделает то же самое (инструментарий байт-кода), но во время выполнения, как в обычном томе
Примечание: рекомендуется увеличить время сборки, если вам не нужно переносить этот код между несколькими провайдерами.
Ромен
Я только что попробовал тот же код с провайдером Hibernate. это работает хорошо. тот же код не работает с Open JPA:(
persistence.xml
<provider>org.hibernate.ejb.HibernatePersistence</provider>
зависимость
<dependency>
<groupId>org.apache.tomee</groupId>
<artifactId>openejb-core-hibernate</artifactId>
<version>8.0.0-SNAPSHOT</version>
<type>pom</type>
<scope>test</scope>
</dependency>