javax.persistence.PersistenceContext Java Examples

The following examples show how to use javax.persistence.PersistenceContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JpaUnitContext.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
private static Map<String, Object> getPersistenceContextProperties(final PersistenceContext persistenceContext) {
    final Map<String, Object> properties = new HashMap<>();
    for (final PersistenceProperty property : persistenceContext.properties()) {
        String propertyValue = property.value();
        Matcher matcher = PROPERTY_PATTERN.matcher(propertyValue);

        while(matcher.find()) {
            String p = matcher.group();
            String systemProperty = p.substring(2, p.length() - 1);
            propertyValue = propertyValue.replace(p, System.getProperty(systemProperty, p));
        }

        properties.put(property.name(), propertyValue);
    }
    return properties;
}
 
Example #2
Source File: PersistenceContextAnnFactory.java    From tomee with Apache License 2.0 6 votes vote down vote up
public PersistenceContextAnn create(final PersistenceContext persistenceContext, final AnnotationDeployer.Member member) throws OpenEJBException {
    if (useAsm) {
        if (member != null) {
            addAnnotations(member.getDeclaringClass());
        }

        String name = persistenceContext.name();
        if (name == null || name.isEmpty()) {
            name = member == null ? null : member.getDeclaringClass().getName() + "/" + member.getName();
        }

        final AsmPersistenceContext asmPersistenceContext = contexts.get(name);
        if (asmPersistenceContext == null) {
            throw new NullPointerException("PersistenceContext " + name + " not found");
        }
        return asmPersistenceContext;
    } else {
        return new DirectPersistenceContext(persistenceContext);
    }
}
 
Example #3
Source File: AnnotationInspectorTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void generateModel() throws Exception {
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    JAnnotationUse jAnnotationUse = jClass.annotate(InitialDataSets.class);
    jAnnotationUse.param("value", "Script.file");
    jClass.annotate(Cleanup.class);
    final JFieldVar jField = jClass.field(JMod.PRIVATE, String.class, "testField");
    jField.annotate(PersistenceContext.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jAnnotationUse = jMethod.annotate(InitialDataSets.class);
    jAnnotationUse.param("value", "InitialDataSets.file");
    jAnnotationUse = jMethod.annotate(ApplyScriptsAfter.class);
    jAnnotationUse.param("value", "ApplyScriptsAfter.file");

    buildModel(testFolder.getRoot(), jCodeModel);

    compileModel(testFolder.getRoot());

    cut = loadClass(testFolder.getRoot(), jClass.name());
}
 
Example #4
Source File: JpaService.java    From kumuluzee with MIT License 6 votes vote down vote up
@Override
public ResourceReferenceFactory<EntityManager> registerPersistenceContextInjectionPoint
        (InjectionPoint injectionPoint) {

    PersistenceUnitHolder holder = PersistenceUnitHolder.getInstance();

    PersistenceContext pc = injectionPoint.getAnnotated().getAnnotation(PersistenceContext
            .class);
    String unitName = pc.unitName();

    if (unitName.isEmpty()) {

        unitName = holder.getDefaultUnitName();

        if (unitName.isEmpty()) {
            throw new NoDefaultPersistenceUnit();
        }
    }

    PersistenceWrapper wrapper = holder.getEntityManagerFactory(unitName);

    return new PersistenceContextResourceFactory(unitName, wrapper.getEntityManagerFactory(),
            wrapper.getTransactionType(), pc.synchronization());
}
 
Example #5
Source File: AnnotationInspectorTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testFieldAnnotationInspection() throws Exception {
    // GIVEN
    final Field field = cut.getDeclaredField("testField");
    final Method method = cut.getDeclaredMethod("testMethod");

    // WHEN
    final AnnotationInspector<PersistenceContext> ai = new AnnotationInspector<>(cut, PersistenceContext.class);

    // THEN
    assertThat(ai.fetchFromField(field), notNullValue());
    assertThat(ai.fetchFromMethod(method), nullValue());
    assertThat(ai.fetchUsingFirst(method), nullValue());
    assertThat(ai.fetchAll().size(), equalTo(1));
    assertThat(ai.getAnnotatedFields().size(), equalTo(1));
    assertThat(ai.getAnnotatedFields(), hasItem(field));
    assertThat(ai.getAnnotatedMethods().isEmpty(), equalTo(Boolean.TRUE));
    assertThat(ai.getAnnotationOnClassLevel(), nullValue());
    assertThat(ai.isDefinedOnField(field), equalTo(Boolean.TRUE));
    assertThat(ai.isDefinedOnAnyField(), equalTo(Boolean.TRUE));
    assertThat(ai.isDefinedOnMethod(method), equalTo(Boolean.FALSE));
    assertThat(ai.isDefinedOnAnyMethod(), equalTo(Boolean.FALSE));
    assertThat(ai.isDefinedOnClassLevel(), equalTo(Boolean.FALSE));
}
 
Example #6
Source File: DataAppLoader.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
@PersistenceContext
public static void loadDiscountRate(EntityManager entityManager){
    DiscountRate dr1 = new DiscountRate('H');
    DiscountRate dr2 = new DiscountRate('M');
    DiscountRate dr3 = new DiscountRate('L');
    DiscountRate dr4 = new DiscountRate('N');
    
    dr1.setRate(0.08);
    dr2.setRate(0.04);
    dr3.setRate(0.02);
    dr4.setRate(0.00);
    
    entityManager.persist(dr1);
    entityManager.persist(dr2);
    entityManager.persist(dr3);
    entityManager.persist(dr4);
}
 
Example #7
Source File: DataAppLoader.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
@PersistenceContext
public static void loadRole(EntityManager entityManager) {
    Role r = new Role('E');
    r.setDescription("Sales Executive, National");
    entityManager.persist(r);
    
    r = new Role('D');
    r.setDescription("District Manager");
    entityManager.persist(r);
    
    r = new Role('T');
    r.setDescription("Sales, Territory");
    entityManager.persist(r);
    
    r = new Role('A');
    r.setDescription("Sales, Associate");
    entityManager.persist(r);
}
 
Example #8
Source File: DataAppLoader.java    From marathonv5 with Apache License 2.0 6 votes vote down vote up
@PersistenceContext
public static void loadRole(EntityManager entityManager) {
    Role r = new Role('E');
    r.setDescription("Sales Executive, National");
    entityManager.persist(r);
    
    r = new Role('D');
    r.setDescription("District Manager");
    entityManager.persist(r);
    
    r = new Role('T');
    r.setDescription("Sales, Territory");
    entityManager.persist(r);
    
    r = new Role('A');
    r.setDescription("Sales, Associate");
    entityManager.persist(r);
}
 
Example #9
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextFieldOfWrongType() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "em");
    emField.annotate(PersistenceContext.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException e) {

        // THEN
        assertThat(e.getMessage(), containsString("annotated with @PersistenceContext is not of type EntityManager"));
    }
}
 
Example #10
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextFieldOfWrongType() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "em");
    emField.annotate(PersistenceContext.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
    assertThat(failure.getException().getMessage(), containsString("annotated with @PersistenceContext is not of type EntityManager"));
}
 
Example #11
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextAndPersistenceUnitFields() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
    emf1Field.annotate(PersistenceContext.class);
    final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    emf2Field.annotate(PersistenceUnit.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
    assertThat(failure.getException().getMessage(), containsString("either @PersistenceUnit or @PersistenceContext"));
}
 
Example #12
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithMultiplePersistenceContextFields() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar em1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em1");
    em1Field.annotate(PersistenceContext.class);
    final JFieldVar em2Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em2");
    em2Field.annotate(PersistenceContext.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(IllegalArgumentException.class));
    assertThat(failure.getException().getMessage(), containsString("Only single field is allowed"));
}
 
Example #13
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextWithKonfiguredUnitNameSpecified() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
    final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class);
    jAnnotation.param("unitName", "test-unit-1");
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
    final BlockJUnit4ClassRunner runner = new BlockJUnit4ClassRunner(cut);

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class);
    verify(listener).testStarted(descriptionCaptor.capture());
    assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
    assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));

    verify(listener).testFinished(descriptionCaptor.capture());
    assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
    assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));
}
 
Example #14
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextWithoutUnitNameSpecified() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
    emField.annotate(PersistenceContext.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("JpaUnitException expected");
    } catch (final JpaUnitException e) {

        // THEN
        assertThat(e.getMessage(), containsString("No Persistence"));
    }
}
 
Example #15
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextAndPersistenceUnitFields() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar emf1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
    emf1Field.annotate(PersistenceContext.class);
    final JFieldVar emf2Field = jClass.field(JMod.PRIVATE, EntityManagerFactory.class, "emf");
    emf2Field.annotate(PersistenceUnit.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException e) {

        // THEN
        assertThat(e.getMessage(), containsString("either @PersistenceUnit or @PersistenceContext"));
    }
}
 
Example #16
Source File: JpaUnitRuleTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithMultiplePersistenceContextFields() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JFieldVar ruleField = jClass.field(JMod.PUBLIC, JpaUnitRule.class, "rule");
    ruleField.annotate(Rule.class);
    final JInvocation instance = JExpr._new(jCodeModel.ref(JpaUnitRule.class)).arg(JExpr.direct("getClass()"));
    ruleField.init(instance);
    final JFieldVar em1Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em1");
    em1Field.annotate(PersistenceContext.class);
    final JFieldVar em2Field = jClass.field(JMod.PRIVATE, EntityManager.class, "em2");
    em2Field.annotate(PersistenceContext.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    try {
        // WHEN
        new JpaUnitRule(cut);
        fail("IllegalArgumentException expected");
    } catch (final IllegalArgumentException e) {

        // THEN
        assertThat(e.getMessage(), containsString("Only single field is allowed"));
    }
}
 
Example #17
Source File: PersistenceInjectionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@PersistenceContext(type = PersistenceContextType.EXTENDED)
public void setEntityManager(EntityManager em) {
	if (this.em != null) {
		throw new IllegalStateException("Already called");
	}
	this.em = em;
}
 
Example #18
Source File: PersistenceInjectionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@PersistenceContext(type = PersistenceContextType.EXTENDED)
public void setEntityManager(EntityManager em) {
	if (this.em != null) {
		throw new IllegalStateException("Already called");
	}
	this.em = em;
}
 
Example #19
Source File: PersistenceInjectionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@PersistenceContext(type = PersistenceContextType.EXTENDED)
public void setEntityManager(EntityManager em) {
	if (this.em != null) {
		throw new IllegalStateException("Already called");
	}
	this.em = em;
}
 
Example #20
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextWithoutUnitNameSpecified() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
    emField.annotate(PersistenceContext.class);
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Failure> failureCaptor = ArgumentCaptor.forClass(Failure.class);
    verify(listener).testFailure(failureCaptor.capture());

    final Failure failure = failureCaptor.getValue();
    assertThat(failure.getException().getClass(), equalTo(JpaUnitException.class));
    assertThat(failure.getException().getMessage(), containsString("No Persistence"));
}
 
Example #21
Source File: JpaUnitRunnerTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testClassWithPersistenceContextWithKonfiguredUnitNameSpecified() throws Exception {
    // GIVEN
    final JCodeModel jCodeModel = new JCodeModel();
    final JPackage jp = jCodeModel.rootPackage();
    final JDefinedClass jClass = jp._class(JMod.PUBLIC, "ClassUnderTest");
    final JAnnotationUse jAnnotationUse = jClass.annotate(RunWith.class);
    jAnnotationUse.param("value", JpaUnitRunner.class);
    final JFieldVar emField = jClass.field(JMod.PRIVATE, EntityManager.class, "em");
    final JAnnotationUse jAnnotation = emField.annotate(PersistenceContext.class);
    jAnnotation.param("unitName", "test-unit-1");
    final JMethod jMethod = jClass.method(JMod.PUBLIC, jCodeModel.VOID, "testMethod");
    jMethod.annotate(Test.class);

    buildModel(testFolder.getRoot(), jCodeModel);
    compileModel(testFolder.getRoot());

    final Class<?> cut = loadClass(testFolder.getRoot(), jClass.name());
    final JpaUnitRunner runner = new JpaUnitRunner(cut);

    final RunListener listener = mock(RunListener.class);
    final RunNotifier notifier = new RunNotifier();
    notifier.addListener(listener);

    // WHEN
    runner.run(notifier);

    // THEN
    final ArgumentCaptor<Description> descriptionCaptor = ArgumentCaptor.forClass(Description.class);
    verify(listener).testStarted(descriptionCaptor.capture());
    assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
    assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));

    verify(listener).testFinished(descriptionCaptor.capture());
    assertThat(descriptionCaptor.getValue().getClassName(), equalTo("ClassUnderTest"));
    assertThat(descriptionCaptor.getValue().getMethodName(), equalTo("testMethod"));
}
 
Example #22
Source File: MetadataExtractorTest.java    From jpa-unit with Apache License 2.0 5 votes vote down vote up
@Test
public void testPersistenceContext() {

    // WHEN
    final AnnotationInspector<PersistenceContext> ai = metadataExtractor.persistenceContext();

    // THEN
    assertThat(ai, notNullValue());
}
 
Example #23
Source File: ReferenceTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateForPersistenceContextField2() throws Exception {
    class Bean {
        @PersistenceContext(name = "other")
        private Object foo;
    }
    Field field = Bean.class.getDeclaredField("foo");
    PersistenceContext ctx = field.getAnnotation(PersistenceContext.class);
    Reference r = Reference.createFor(ctx, field);
    assertEquals(EntityManager.class, r.getInterfaceOrClass());
    assertEquals("other", r.getName());
}
 
Example #24
Source File: Reference.java    From development with Apache License 2.0 5 votes vote down vote up
public static Reference createFor(PersistenceContext persistenceContext,
        Field field) {
    final String name;
    if (persistenceContext.name().length() > 0) {
        name = persistenceContext.name();
    } else {
        name = field.getDeclaringClass().getName() + "/" + field.getName();
    }
    return new Reference(EntityManager.class, name, field);
}
 
Example #25
Source File: ReferenceTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateForPersistenceContextField1() throws Exception {
    class Bean {
        @PersistenceContext
        private Object foo;
    }
    Field field = Bean.class.getDeclaredField("foo");
    PersistenceContext ctx = field.getAnnotation(PersistenceContext.class);
    Reference r = Reference.createFor(ctx, field);
    assertEquals(EntityManager.class, r.getInterfaceOrClass());
    assertEquals(Bean.class.getName() + "/foo", r.getName());
}
 
Example #26
Source File: PersistenceContextInjector.java    From testfun with Apache License 2.0 5 votes vote down vote up
@Override
public <T> void inject(T target, Field field) {
    if (field.isAnnotationPresent(PersistenceContext.class)) {

        // Make sure the field is of EntityManager interface
        Class<?> fieldClass = InjectionUtils.getFieldInterface(target, field);
        if (!EntityManager.class.equals(fieldClass)) {
            throw new EjbWithMockitoRunnerException(InjectionUtils.getFieldDescription(field, target) + " is annotated with PersistenceContext but isn't EntityManager");
        }

        // Assign the EntityManager to the field
        InjectionUtils.assignObjectToField(target, field, SingletonEntityManager.getInstance());
    }
}
 
Example #27
Source File: PersistenceContextAnnFactoryTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
private static void assertEq(final PersistenceContext annotation, final PersistenceContextAnn wrapper) {
    if (annotation.name().length() > 0) {
        assertEquals(annotation.name(), wrapper.name());
    }
    assertEquals(annotation.unitName(), wrapper.unitName());
    assertEquals(annotation.type().toString(), wrapper.type());

    final Map<String, String> properties = new HashMap<>();
    for (final PersistenceProperty property : annotation.properties()) {
        properties.put(property.name(), property.value());
    }
    assertEquals(properties, wrapper.properties());
}
 
Example #28
Source File: ForumServiceImpl.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
@Override
@Transactional
public Post findById(Long id) {
    Post post = postDAO.findById(id);

    org.hibernate.engine.spi.PersistenceContext persistenceContext = getHibernatePersistenceContext();

    EntityEntry entityEntry = persistenceContext.getEntry(post);
    assertNotNull(entityEntry.getLoadedState());

    return post;
}
 
Example #29
Source File: BatchUnitTestProducer.java    From wow-auctions with GNU General Public License v3.0 5 votes vote down vote up
@Produces
@PersistenceContext
@Singleton
public EntityManager create() {
    Map<String, String> properties = new HashMap<>();
    properties.put("javax.persistence.transactionType", "RESOURCE_LOCAL");
    properties.put("hibernate.show_sql", "true");
    return Persistence.createEntityManagerFactory("wowAuctions", properties).createEntityManager();
}
 
Example #30
Source File: BasicJpaInjectionServices.java    From hammock with Apache License 2.0 5 votes vote down vote up
@Override
public ResourceReferenceFactory<EntityManager> registerPersistenceContextInjectionPoint(InjectionPoint ip) {
    PersistenceContext pc = ip.getAnnotated().getAnnotation(PersistenceContext.class);
    if (pc == null) {
        throw new IllegalArgumentException("No @PersistenceContext annotation found on EntityManager");
    }
    String name = pc.unitName();
    LOG.info("Creating EntityManagerReferenceFactory for unit " + name);
    return new EntityManagerReferenceFactory(name);
}