Java Code Examples for javax.persistence.PersistenceContext

The following are top voted examples for showing how to use javax.persistence.PersistenceContext. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: marathonv5   File: DataAppLoader.java   View source code 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 2
Project: marathonv5   File: DataAppLoader.java   View source code 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 3
Project: marathonv5   File: DataAppLoader.java   View source code 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 4
Project: marathonv5   File: DataAppLoader.java   View source code 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 5
Project: aries-jpa   File: PersistenceAnnotatedType.java   View source code 6 votes vote down vote up
private <X> AnnotatedField<X> decorateContext(AnnotatedField<X> field) {
    final PersistenceContext persistenceContext = field.getAnnotation(PersistenceContext.class);
    final UniqueIdentifier identifier = UniqueIdentifierLitteral.random();

    Set<Annotation> templateQualifiers = new HashSet<>();
    templateQualifiers.add(ServiceLiteral.SERVICE);
    if (hasUnitName(persistenceContext)) {
        templateQualifiers.add(new FilterLiteral("(osgi.unit.name=" + persistenceContext.unitName() + ")"));
    }
    Bean<JpaTemplate> bean = manager.getExtension(OsgiExtension.class)
            .globalDependency(JpaTemplate.class, templateQualifiers);

    Set<Annotation> qualifiers = new HashSet<>();
    qualifiers.add(identifier);
    Bean<EntityManager> b = new SimpleBean<>(EntityManager.class, Dependent.class, Collections.singleton(EntityManager.class), qualifiers, () -> {
        CreationalContext<JpaTemplate> context = manager.createCreationalContext(bean);
        JpaTemplate template = (JpaTemplate) manager.getReference(bean, JpaTemplate.class, context);
        return EntityManagerProducer.create(template);
    });
    beans.add(b);

    Set<Annotation> fieldAnnotations = new HashSet<>();
    fieldAnnotations.add(InjectLiteral.INJECT);
    fieldAnnotations.add(identifier);
    return new SyntheticAnnotatedField<>(field, fieldAnnotations);
}
 
Example 6
Project: iws   File: CommitteeSpringClient.java   View source code 6 votes vote down vote up
/**
 * Injects the {@code EntityManager} instance required to invoke our
 * transactional daos. The EntityManager instance can only be injected into
 * the Spring Beans, we cannot create a Spring Bean for the Committees EJB
 * otherwise.
 *
 * @param entityManager Spring controlled EntityManager instance
 */
@PersistenceContext
public void init(final EntityManager entityManager) {
    // Create the Notification Spy, and inject it
    final Notifications notitications = NotificationSpy.getInstance();
    final NotificationManagerScheduler notificationBean = new NotificationManagerScheduler();
    notificationBean.setNotifications(notitications);

    // Create a new SessionRequestBean instance with our entityManager
    final SessionRequestBean sessionRequestBean = new SessionRequestBean();
    sessionRequestBean.setEntityManager(entityManager);
    sessionRequestBean.setSettings(Beans.settings());
    sessionRequestBean.postConstruct();

    // Create an Committees EJB, and inject the EntityManager & Notification Spy
    final CommitteeBean committeeBean = new CommitteeBean();
    committeeBean.setEntityManager(entityManager);
    committeeBean.setNotificationManager(notificationBean);
    committeeBean.setSessionRequestBean(sessionRequestBean);
    committeeBean.setSettings(Beans.settings());
    committeeBean.postConstruct();

    // Set our Committees implementation to the Committees EJB,
    // running withing a "Spring Container".
    client = committeeBean;
}
 
Example 7
Project: iws   File: ExchangeSpringClient.java   View source code 6 votes vote down vote up
/**
 * Injects the {@code EntityManager} instance required to invoke our
 * transactional DAOs. The EntityManager instance can only be injected into
 * the Spring Beans, we cannot create a Spring Bean for the Exchange EJB
 * otherwise.
 *
 * @param entityManager Spring controlled EntityManager instance
 */
@PersistenceContext
public void init(final EntityManager entityManager) {
    // Create the Notification Spy, and inject it
    final Notifications notitications = NotificationSpy.getInstance();
    final NotificationManagerScheduler notificationBean = new NotificationManagerScheduler();
    notificationBean.setNotifications(notitications);

    // Create a new SessionRequestBean instance with our entityManager
    final SessionRequestBean sessionRequestBean = new SessionRequestBean();
    sessionRequestBean.setEntityManager(entityManager);
    sessionRequestBean.setSettings(Beans.settings());
    sessionRequestBean.postConstruct();

    // Create an Exchange EJB, and inject the EntityManager & Notification Spy
    final ExchangeBean exchangeBean = new ExchangeBean();
    exchangeBean.setEntityManager(entityManager);
    exchangeBean.setNotificationManager(notificationBean);
    exchangeBean.setSessionRequestBean(sessionRequestBean);
    exchangeBean.setSettings(Beans.settings());
    exchangeBean.postConstruct();

    // Set our Exchange implementation to the Exchange EJB, running within
    // a "Spring Container".
    client = exchangeBean;
}
 
Example 8
Project: iws   File: AccessSpringClient.java   View source code 6 votes vote down vote up
/**
 * Injects the {@code EntityManager} instance required to invoke our
 * transactional DAOs. The EntityManager instance can only be injected into
 * the Spring Beans, we cannot create a Spring Bean for the Access EJB
 * otherwise.
 *
 * @param entityManager Spring controlled EntityManager instance
 */
@PersistenceContext
public void init(final EntityManager entityManager) {
    // Create the Notification Spy, and inject it
    final Notifications notitications = NotificationSpy.getInstance();
    final NotificationManagerScheduler notificationBean = new NotificationManagerScheduler();
    notificationBean.setNotifications(notitications);

    // Create a new SessionRequestBean instance with our entityManager
    final SessionRequestBean sessionRequestBean = new SessionRequestBean();
    sessionRequestBean.setEntityManager(entityManager);
    sessionRequestBean.setSettings(Beans.settings());
    sessionRequestBean.postConstruct();

    // Create an Access EJB, and inject the EntityManager & Notification Spy
    final AccessBean accessBean = new AccessBean();
    accessBean.setEntityManager(entityManager);
    accessBean.setNotificationManager(notificationBean);
    accessBean.setSessionRequestBean(sessionRequestBean);
    accessBean.setSettings(Beans.settings());
    accessBean.postConstruct();

    // Set our Access implementation to the Access EJB, running within a
    // "Spring Container".
    client = accessBean;
}
 
Example 9
Project: iws   File: StorageSpringClient.java   View source code 6 votes vote down vote up
/**
 * Injects the {@code EntityManager} instance required to invoke our
 * transactional DAOs. The EntityManager instance can only be injected into
 * the Spring Beans, we cannot create a Spring Bean for the Committees EJB
 * otherwise.
 *
 * @param entityManager Spring controlled EntityManager instance
 */
@PersistenceContext
public void init(final EntityManager entityManager) {
    // Create the Notification Spy, and inject it
    final Notifications notifications = NotificationSpy.getInstance();
    final NotificationManagerScheduler notificationBean = new NotificationManagerScheduler();
    notificationBean.setNotifications(notifications);

    // Create a new SessionRequestBean instance with our entityManager
    final SessionRequestBean sessionRequestBean = new SessionRequestBean();
    sessionRequestBean.setEntityManager(entityManager);
    sessionRequestBean.setSettings(Beans.settings());
    sessionRequestBean.postConstruct();

    // Create an Committees EJB, and inject the EntityManager & Notification Spy
    final StorageBean storageBean = new StorageBean();
    storageBean.setEntityManager(entityManager);
    storageBean.setNotificationManager(notificationBean);
    storageBean.setSessionRequestBean(sessionRequestBean);
    storageBean.setSettings(Beans.settings());
    storageBean.postConstruct();

    // Set our Committees implementation to the Committees EJB,
    // running withing a "Spring Container".
    client = storageBean;
}
 
Example 10
Project: iws   File: StudentSpringClient.java   View source code 6 votes vote down vote up
/**
 * Injects the {@code EntityManager} instance required to invoke our
 * transactional DAOs. The EntityManager instance can only be injected into
 * the Spring Beans, we cannot create a Spring Bean for the Exchange EJB
 * otherwise.
 *
 * @param entityManager Spring controlled EntityManager instance
 */
@PersistenceContext
public void init(final EntityManager entityManager) {
    // Create the Notification Spy, and inject it
    final Notifications notitications = NotificationSpy.getInstance();
    final NotificationManagerScheduler notificationBean = new NotificationManagerScheduler();
    notificationBean.setNotifications(notitications);

    // Create a new SessionRequestBean instance with our entityManager
    final SessionRequestBean sessionRequestBean = new SessionRequestBean();
    sessionRequestBean.setEntityManager(entityManager);
    sessionRequestBean.setSettings(Beans.settings());
    sessionRequestBean.postConstruct();

    // Create an Exchange EJB, and inject the EntityManager & Notification Spy
    final StudentBean studentBean = new StudentBean();
    studentBean.setEntityManager(entityManager);
    studentBean.setNotificationManager(notificationBean);
    studentBean.setSessionRequestBean(sessionRequestBean);
    studentBean.setSettings(Beans.settings());
    studentBean.postConstruct();

    // Set our Exchange implementation to the Exchange EJB, running withing
    // a "Spring Container".
    client = studentBean;
}
 
Example 11
Project: iws   File: AdministrationSpringClient.java   View source code 6 votes vote down vote up
/**
 * Injects the {@code EntityManager} instance required to invoke our
 * transactional DAOs. The EntityManager instance can only be injected into
 * the Spring Beans, we cannot create a Spring Bean for the Administration
 * EJB otherwise.
 *
 * @param entityManager Spring controlled EntityManager instance
 */
@PersistenceContext
public void init(final EntityManager entityManager) {
    // Create the Notification Spy, and inject it
    final Notifications notitications = NotificationSpy.getInstance();
    final NotificationManagerScheduler notificationBean = new NotificationManagerScheduler();
    notificationBean.setNotifications(notitications);

    // Create a new SessionRequestBean instance with our entityManager
    final SessionRequestBean sessionRequestBean = new SessionRequestBean();
    sessionRequestBean.setEntityManager(entityManager);
    sessionRequestBean.setSettings(Beans.settings());
    sessionRequestBean.postConstruct();

    // Create an Administration EJB, and inject the EntityManager & Notification Spy
    final AdministrationBean administrationBean = new AdministrationBean();
    administrationBean.setEntityManager(entityManager);
    administrationBean.setNotificationManager(notificationBean);
    administrationBean.setSessionRequestBean(sessionRequestBean);
    administrationBean.setSettings(Beans.settings());
    administrationBean.postConstruct();

    // Set our Administration implementation to the Administration EJB,
    // running withing a "Spring Container".
    client = administrationBean;
}
 
Example 12
Project: jpa-unit   File: JpaUnitRuleTest.java   View source code 6 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 13
Project: jpa-unit   File: JpaUnitContext.java   View source code 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 14
Project: jpa-unit   File: AnnotationInspectorTest.java   View source code 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 15
Project: jpa-unit   File: AnnotationInspectorTest.java   View source code 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 16
Project: jspare-container   File: PersistenceContextInjectStrategy.java   View source code 6 votes vote down vote up
@Override
public void inject(Object result, Field field) {
    try {

        String unitName = field.getAnnotation(PersistenceContext.class).unitName();
        if (StringUtils.isEmpty(unitName))
            unitName = PersistenceUnitProvider.DEFAULT_DS;

        if (!field.getType().equals(EntityManager.class)) {

            log.error("Failed to create PersistenceContext, type of field is not a EntityManager");
            return;
        }

        EntityManager em = provider.getProvider().createEntityManager();

        field.setAccessible(true);
        field.set(result, em);
    } catch (Exception e) {

        log.error("Failed to create PersistenceContext", e);
    }
}
 
Example 17
Project: kumuluzee   File: JpaService.java   View source code 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 18
Project: tapestry-jpa-transactions   File: TransactionalUnitJpaTransactionAdvisor.java   View source code 6 votes vote down vote up
@Override
public void addTransactionCommitAdvice(MethodAdviceReceiver receiver)
{
    for (final Method m : receiver.getInterface().getMethods())
    {
        if (m.getAnnotation(CommitAfter.class) != null)
        {
            PersistenceContext annotation = receiver.getMethodAnnotation(m, PersistenceContext.class);

            MethodAdvice advice =
                    annotation == null ? shared : new TransactionalUnitMethodAdvice(manager, annotation);

            receiver.adviseMethod(m, advice);
        }
    }
}
 
Example 19
Project: javaee-samples   File: InjectionRunner.java   View source code 6 votes vote down vote up
private static JPARule createJPARule(PersistenceContext ctx, Object test) {
    DatabaseConfiguration config = findOnTest(DatabaseConfiguration.class, test);

    if (config == null) {
        return new JPARule(ctx, H2, DEFAULT_STORAGE, DEFAULT_MODE);
    }

    switch (config.value()) {
        case H2:
            return new JPARule(ctx, H2, config.h2().storage(), config.h2().mode());
        case UNDEFINED:
        default:
            Map<String, String> properties = new HashMap<>();
            for (PersistenceProperty property : ctx.properties()) {
                properties.put(property.name(), property.value());
            }
            return unitName(ctx.unitName())
                    .database(UNDEFINED)
                    .noInternalProperties()
                    .properties(properties)
                    .build();
    }
}
 
Example 20
Project: javaee-samples   File: BothPersistenceDefinitionsTest.java   View source code 6 votes vote down vote up
@Test
@PersistenceContext(unitName = "containerless-test-pu")
public void shouldPreferMethodPU$NegativeTest() {
    assertThat(jpa)
            .isNotNull();

    assertThat(jpa)
            .extracting(JPARule::getUnitName)
            .containsExactly("containerless-test-pu");

    assertThat(em)
            .isNotNull();

    EntityWithTableGenerator e = new EntityWithTableGenerator();
    exception.expect(IllegalArgumentException.class);
    exception.expectMessage("Unknown entity: javaee.samples.frameworks.injection.tablegenerator.EntityWithTableGenerator");
    em.persist(e);
}
 
Example 21
Project: javaee-samples   File: BothPersistenceDefinitionsTest.java   View source code 6 votes vote down vote up
@Test
@PersistenceContext(unitName = "containerless-test-pu")
@Transactional
public void shouldPreferMethodPU() {
    assertThat(jpa)
            .isNotNull();

    assertThat(jpa)
            .extracting(JPARule::getUnitName)
            .containsExactly("containerless-test-pu");

    assertThat(em)
            .isNotNull();

    MyEntity e = new MyEntity();
    em.persist(e);
}
 
Example 22
Project: tomee   File: PersistenceContextAnnFactory.java   View source code 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.equals("")) {
            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 23
Project: lightmare   File: BeanDeployer.java   View source code 6 votes vote down vote up
/**
 * Retrieves and caches {@link Field}s with injection
 *
 * @param field
 * @throws IOException
 */
private void retriveConnection(Field field) throws IOException {

    PersistenceContext context = field.getAnnotation(PersistenceContext.class);
    Resource resource = field.getAnnotation(Resource.class);
    PersistenceUnit unit = field.getAnnotation(PersistenceUnit.class);
    EJB ejbAnnot = field.getAnnotation(EJB.class);
    if (ObjectUtils.notNull(context)) {
        identifyConnections(context, field);
        addAccessibleField(field);
    } else if (ObjectUtils.notNull(resource)) {
        metaData.setTransactionField(field);
        addAccessibleField(field);
    } else if (ObjectUtils.notNull(unit)) {
        addUnitField(field);
        addAccessibleField(field);
    } else if (ObjectUtils.notNull(ejbAnnot)) {
        // caches EJB annotated fields
        cacheInjectFields(field);
        addAccessibleField(field);
    }
}
 
Example 24
Project: testee.fi   File: JpaInjectionServicesImpl.java   View source code 5 votes vote down vote up
@Override
public ResourceReferenceFactory<EntityManager> registerPersistenceContextInjectionPoint(
        final InjectionPoint injectionPoint
) {
    final PersistenceContext persistenceContext = injectionPoint
            .getAnnotated()
            .getAnnotation(PersistenceContext.class);
    final String unitName = persistenceContext.unitName();
    return registerPersistenceContextInjectionPoint(unitName);
}
 
Example 25
Project: aries-jpa   File: AnnotationScannerTest.java   View source code 5 votes vote down vote up
@Test
public void getPCAnnotatedMembersTest() {
    AnnotationScanner scanner = new AnnotationScanner();
    List<AccessibleObject> members = scanner.getJpaAnnotatedMembers(TestClass.class, PersistenceContext.class);
    Assert.assertEquals(1, members.size());
    AccessibleObject member = members.get(0);
    Assert.assertEquals(Field.class, member.getClass());
    Field field = (Field)member;
    Assert.assertEquals("em", field.getName());
}
 
Example 26
Project: aries-jpa   File: JpaExtension.java   View source code 5 votes vote down vote up
public <T> void processAnnotatedType(@Observes ProcessAnnotatedType<T> event, BeanManager manager) {
    boolean hasPersistenceField = false;
    for (AnnotatedField<? super T> field : event.getAnnotatedType().getFields()) {
        if (field.isAnnotationPresent(PersistenceContext.class)
                || field.isAnnotationPresent(PersistenceUnit.class)) {
            hasPersistenceField = true;
            break;
        }
    }
    if (hasPersistenceField) {
        PersistenceAnnotatedType<T> pat = new PersistenceAnnotatedType<T>(manager, event.getAnnotatedType());
        beans.addAll(pat.getProducers());
        event.setAnnotatedType(pat);
    }
}
 
Example 27
Project: aries-jpa   File: PersistenceAnnotatedType.java   View source code 5 votes vote down vote up
public PersistenceAnnotatedType(BeanManager manager, AnnotatedType<T> delegate) {
    super(delegate);
    this.manager = manager;
    this.fields = new HashSet<>();
    for (AnnotatedField<? super T> field : delegate.getFields()) {
        if (field.isAnnotationPresent(PersistenceContext.class)) {
            field = decorateContext(field);
        } else if (field.isAnnotationPresent(PersistenceUnit.class)) {
            field = decorateUnit(field);
        }
        this.fields.add(field);
    }
}
 
Example 28
Project: oscm   File: ReferenceTest.java   View source code 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 29
Project: oscm   File: ReferenceTest.java   View source code 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 30
Project: oscm   File: Reference.java   View source code 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 31
Project: oscm   File: ReferenceTest.java   View source code 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 32
Project: oscm   File: ReferenceTest.java   View source code 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 33
Project: minijax   File: Key.java   View source code 5 votes vote down vote up
private void processAnnotation(final Annotation annotation) {
    final Class<? extends Annotation> annType = annotation.annotationType();

    if (annType == Context.class) {
        setStrategy(Strategy.CONTEXT);

    } else if (annType == CookieParam.class) {
        processCookieParamAnnotation((CookieParam) annotation);

    } else if (annType == FormParam.class) {
        processFormParamAnnotation((FormParam) annotation);

    } else if (annType == HeaderParam.class) {
        processHeaderParamAnnotation((HeaderParam) annotation);

    } else if (annType == Named.class) {
        processNamedAnnotation((Named) annotation);

    } else if (annType == PathParam.class) {
        processPathParamAnnotation((PathParam) annotation);

    } else if (annType == OptionalClasses.PERSISTENCE_CONTEXT) {
        processPersistenceContextAnnotation((PersistenceContext) annotation);

    } else if (annType == QueryParam.class) {
        processQueryParamAnnotation((QueryParam) annotation);

    } else if (annType == DefaultValue.class) {
        defaultValue = (DefaultValue) annotation;

    } else if (annType.isAnnotationPresent(Qualifier.class)) {
        processQualifierAnnotation(annType);
    }
}
 
Example 34
Project: spring4-understanding   File: PersistenceAnnotationBeanPostProcessor.java   View source code 5 votes vote down vote up
public PersistenceElement(Member member, AnnotatedElement ae, PropertyDescriptor pd) {
	super(member, pd);
	PersistenceContext pc = ae.getAnnotation(PersistenceContext.class);
	PersistenceUnit pu = ae.getAnnotation(PersistenceUnit.class);
	Class<?> resourceType = EntityManager.class;
	if (pc != null) {
		if (pu != null) {
			throw new IllegalStateException("Member may only be annotated with either " +
					"@PersistenceContext or @PersistenceUnit, not both: " + member);
		}
		Properties properties = null;
		PersistenceProperty[] pps = pc.properties();
		if (!ObjectUtils.isEmpty(pps)) {
			properties = new Properties();
			for (PersistenceProperty pp : pps) {
				properties.setProperty(pp.name(), pp.value());
			}
		}
		this.unitName = pc.unitName();
		this.type = pc.type();
		this.synchronizedWithTransaction = (synchronizationAttribute == null ||
				"SYNCHRONIZED".equals(ReflectionUtils.invokeMethod(synchronizationAttribute, pc).toString()));
		this.properties = properties;
	}
	else {
		resourceType = EntityManagerFactory.class;
		this.unitName = pu.unitName();
	}
	checkResourceType(resourceType);
}
 
Example 35
Project: spring4-understanding   File: PersistenceInjectionTests.java   View source code 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 36
Project: unitils   File: JpaModule.java   View source code 5 votes vote down vote up
/**
 * Injects the currently active JPA <code>EntityManager</code> into all fields and methods that are
 * annotated with <code>javax.persistence.PersistenceContext</code>
 *
 * @param testObject The test object, not null
 */
public void injectEntityManager(Object testObject, Object target) {
	Set<Field> fields = getFieldsAnnotatedWith(target.getClass(), PersistenceContext.class);
	Set<Method> methods = getMethodsAnnotatedWith(target.getClass(), PersistenceContext.class);
	if (fields.isEmpty() && methods.isEmpty()) {
        // Jump out to make sure that we don't try to instantiate the EntityManagerFactory
        return;
    }
	
	EntityManager entityManager = getPersistenceContext(testObject);
	setFieldAndSetterValue(target, fields, methods, entityManager);
}
 
Example 37
Project: jpa-unit   File: JpaUnitRuleTest.java   View source code 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 38
Project: jpa-unit   File: JpaUnitRuleTest.java   View source code 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 39
Project: jpa-unit   File: JpaUnitRuleTest.java   View source code 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 40
Project: jpa-unit   File: JpaUnitRuleTest.java   View source code 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"));
    }
}