Java 类javax.persistence.PersistenceContext 实例源码

项目:marathonv5    文件:DataAppLoader.java   
@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);
}
项目:marathonv5    文件:DataAppLoader.java   
@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);
}
项目:marathonv5    文件:DataAppLoader.java   
@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);
}
项目:marathonv5    文件:DataAppLoader.java   
@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);
}
项目:aries-jpa    文件:PersistenceAnnotatedType.java   
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);
}
项目:iws    文件:CommitteeSpringClient.java   
/**
 * 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;
}
项目:iws    文件:ExchangeSpringClient.java   
/**
 * 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;
}
项目:iws    文件:AccessSpringClient.java   
/**
 * 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;
}
项目:iws    文件:StorageSpringClient.java   
/**
 * 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;
}
项目:iws    文件:StudentSpringClient.java   
/**
 * 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;
}
项目:iws    文件:AdministrationSpringClient.java   
/**
 * 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;
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
}
项目:jpa-unit    文件:JpaUnitContext.java   
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;
}
项目:jpa-unit    文件:AnnotationInspectorTest.java   
@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());
}
项目:jpa-unit    文件:AnnotationInspectorTest.java   
@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));
}
项目:jspare-container    文件:PersistenceContextInjectStrategy.java   
@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);
    }
}
项目:kumuluzee    文件:JpaService.java   
@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());
}
项目:tapestry-jpa-transactions    文件:TransactionalUnitJpaTransactionAdvisor.java   
@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);
        }
    }
}
项目:javaee-samples    文件:InjectionRunner.java   
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();
    }
}
项目:javaee-samples    文件:BothPersistenceDefinitionsTest.java   
@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);
}
项目:javaee-samples    文件:BothPersistenceDefinitionsTest.java   
@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);
}
项目:tomee    文件:PersistenceContextAnnFactory.java   
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);
    }
}
项目:lightmare    文件:BeanDeployer.java   
/**
 * 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);
    }
}
项目:testee.fi    文件:JpaInjectionServicesImpl.java   
@Override
public ResourceReferenceFactory<EntityManager> registerPersistenceContextInjectionPoint(
        final InjectionPoint injectionPoint
) {
    final PersistenceContext persistenceContext = injectionPoint
            .getAnnotated()
            .getAnnotation(PersistenceContext.class);
    final String unitName = persistenceContext.unitName();
    return registerPersistenceContextInjectionPoint(unitName);
}
项目:aries-jpa    文件:AnnotationScannerTest.java   
@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());
}
项目:aries-jpa    文件:JpaExtension.java   
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);
    }
}
项目:aries-jpa    文件:PersistenceAnnotatedType.java   
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);
    }
}
项目:oscm    文件:ReferenceTest.java   
@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());
}
项目:oscm    文件:ReferenceTest.java   
@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());
}
项目:oscm    文件:Reference.java   
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);
}
项目:oscm    文件:ReferenceTest.java   
@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());
}
项目:oscm    文件:ReferenceTest.java   
@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());
}
项目:minijax    文件:Key.java   
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);
    }
}
项目:spring4-understanding    文件:PersistenceAnnotationBeanPostProcessor.java   
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);
}
项目:spring4-understanding    文件:PersistenceInjectionTests.java   
@PersistenceContext(type = PersistenceContextType.EXTENDED)
public void setEntityManager(EntityManager em) {
    if (this.em != null) {
        throw new IllegalStateException("Already called");
    }
    this.em = em;
}
项目:unitils    文件:JpaModule.java   
/**
 * 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);
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
    }
}
项目:jpa-unit    文件:JpaUnitRuleTest.java   
@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"));
    }
}