Code Monkey home page Code Monkey logo

cdi's Introduction

MyBatis CDI Extension

Java CI Coverage Status Maven central Sonatype Nexus (Snapshots) License

mybatis-logo

MyBatis-CDI extension takes care of the lifecycle of MyBatis mappers and SqlSessions. MyBatis components are directly injected into your CDI beans ready to be used, there is no need to create or destroy them. It also provides local and JTA transaction support based on the @Transactional annotation.

Compatibility

CDI API VERSION JDK 17 JDK 11 JDK 8
cdi-1.0 (not supported) N N N
cdi-1.1 Y Y Y
cdi-1.2 Y Y Y
cdi-2.0 Y Y Y
cdi-3.0 Y Y N
cdi-4.0 Y Y N
cdi-4.1 Y N N

JavaEE is 1.1.4 and is now no longer our focus

JakartaEE is 2.0.0 and is the main focus

Jdk17+ requires jboss-classfilewriter to be at 1.2.5 or it will error, classfilewriter

Building from tag for javax namespace

Maven does not allow multiple auto activated profiles (ie activateByDefault and Jdk). This project supports 3 different CDI support levels currently and was set to default to cdi-1.2. Jdk 8 does not allow add opens and this is needed now for jdk 17. We further are supporting jakarta EE packaging in addition to java EE packaging. This results is a tricky situation. Therefore, we have opted to no longer use activateByDefault which means a build without providing a profile will fail with missing classes. Github actions is provisioned to always provide the specific cdi-api profile. Any localized usage must now do the same as defined below.

The cdi profile can be cdi-1.1, cdi-1.2, or cdi-2.0 and required to run with any of the following.

  • mvn clean install -P"cdi-1.1"
  • mvn clean install -P"cdi-1.2"
  • mvn clean install -P"cdi-2.0"

Building from master

Normal maven build without any special profiles necessary. This line is Jakarta.

Testing with Arquillian (for javaEE, has not been checked with jakarta)

In order to test with Arquillian, one class needs to be added to 'JavaArchive' in order for this to load properly. Add 'SqlSessionManagerRegistry.class'.

See attachment on #86 from 2021-12-30 ArquillianMybatisExample.zip here. This is to be run under jdk 8 to be error free but will run as-is under jdk 11 with an invocation error which still allows it to run. Further updates are needed to get this code example current.

Essentials

Contributed Examples

  • Ready to deploy sample web app (Jee7): samples

cdi's People

Contributors

awxiaoxian2020 avatar dependabot-preview[bot] avatar dependabot[bot] avatar emacarron avatar hazendaz avatar hboutemy avatar kazuki43zoo avatar mazerty avatar mcbeelen avatar mnesarco avatar mwlynch avatar renovate[bot] avatar simonetripodi avatar theonlyal avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cdi's Issues

How to modify java:comp/BeanManager to java:comp/env/BeanManager?

InitialContext.doLookup("java:comp/BeanManager") in org.mybatis.cdi.CDIUtils.getBeanManager()

Jetty only allows you to bind entries to java:comp/env, so the BeanManager will be available at java:comp/env/BeanManager

How to modify java:comp/BeanManager to java:comp/env/BeanManager?

Thanks!

Question/Issue about Mybatis-cdi @Mapper discovery

Hi there,

We use mybatis-cdi in combination with java8. With the default implementation now possible in interfaces this makes code like this possible.

@Inject
  public ItemRepoResolver(@Any Instance<ItemMapper<?>> itemMappers) {
    this.itemMappers = itemMappers;
  }

So we inject a list of Mappers of type ItemMapper and each mapper can say for which type it can be used. For example:

public interface SavingsAccountMapper extends ItemMapper<SavingsAccount> {

  ..some mapper code...

  @Override
  default Class<SavingsAccount> forType() {
    return SavingsAccount.class;
  }
}

But since we do not use @Inject @Mapper SavingsAccountMapper this mapper is not initialized. We can force this initialization by adding this field but we do not need this.

So my question/issue is. Is is possible to inject a list of Mybatis Mappers without the need to inject them in fields individually?

Thanks,
Sander

Not able to make it work as a WildFly 8.1.0 module

Hi,

I have been trying to make it work in WildFly 8.1.0. My deployment is a jar file containing a couple of MDBs.

One issue i have is that i need to bundle my ejb-jar in an ear together with mybatis plus the cdi extension. I am not able to make it work with a module.

This is my module.xml

<module xmlns="urn:jboss:module:1.3" name="org.mybatis.mybatis">

    <resources>
        <resource-root path="mybatis-3.2.7.jar"/>
        <resource-root path="mybatis-cdi-1.0.0-beta1.jar"/>
    </resources>
    <dependencies>
        <module name="javax.enterprise.api"/>
        <module name="javax.api"/>
    <module name="org.javassist"/>  
    <module name="javax.transaction.api"/> 
    </dependencies> 
</module> 

and this is my deployment-structure.xml

<?xml version="1.0" encoding="UTF-8"?>
<jboss-deployment-structure>
    <deployment>
        <dependencies>
            <module name="org.jboss.logmanager"/>
            <module name="org.slf4j"/>
            <module name="org.mybatis.mybatis"/>

        </dependencies>
    </deployment>
</jboss-deployment-structure>

Anybody more luck with this?

tx.,

issue with micro profile standard

Hi,
When I use mybatis-cdi with full JEE 7 app server it is working fine without any issue.But when I use microprofile like kumuluz I am getting following exception

 Caused by: java.lang.RuntimeException: javax.naming.NameNotFoundException; remaining name 
 'BeanManager'
	at org.mybatis.cdi.CDIUtils.getBeanManager(CDIUtils.java:67)
	at org.mybatis.cdi.CDIUtils.findSqlSessionFactory(CDIUtils.java:94)
	at org.mybatis.cdi.SerializableMapperProxy.getMapper(SerializableMapperProxy.java:63)
	at org.mybatis.cdi.SerializableMapperProxy.<init>(SerializableMapperProxy.java:50)
	at org.mybatis.cdi.MyBatisBean.create(MyBatisBean.java:124)
	at org.jboss.weld.context.unbound.DependentContextImpl.get(DependentContextImpl.java:70)
	at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.get(ContextualInstanceStrategy.java:100)
	at org.jboss.weld.bean.ContextualInstance.get(ContextualInstance.java:50)
	at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:786)

I fixed this by replacing below method

private static BeanManager getBeanManager() {
    try {
      return InitialContext.doLookup(JNDI.NAME);
    } catch (NamingException e) {
      throw new RuntimeException(e);
    }
  }

With

 private static BeanManager getBeanManager() {
    return CDI.current().getBeanManager();
  }

since CDI utility is only available CDI 1.1+ .

github is behaving very strange...

pr #93 is merged. It shows that way when pulling. Not sure what is going on as I'ver seen this before. The PR showed merged once then back to open. Just opening this in case we end up with some issue here we need to force push to fix.

UnserializableDependencyException

Hello group,

I am trying to use MyBatis-CDI with a new JSF project. I have a ViewScoped Bean and want to inject a Mapper.

This leads to the following exception during startup:

Caused by: org.jboss.weld.exceptions.UnserializableDependencyException: 
WELD-001413: The bean Managed Bean [class de.e2n.gastroapp.admin.Home] with qualifiers
[@Default @Named @Any] declares a passivating scope but has a non-passivation-capable
dependency org.mybatis.cdi.MyBatisBean@60872782

If I change the scope from ViewScope to RequestScoped it works. SessionScoped and ApplicationScoped yield the same exception.

Should I provide a test case?

Versions:
Apache Tomcat 8.0.32
Mojarra 2.2.13
Weld 2.2.16.Final
MyBatis 3.3.1
MyBatis-CDI 1.0.0-beta3

Possibility to use a certain environment by a Qualifier

Feature Request

It would be great to be able to use a specified environment by using a custom qualifier.

Currently I have to implement a @Named producer for each environment I want to use.
It would be much easier to have something like that:

@Inject 
@Environment("env")
UserMapper userMapper;

I do not know if it is feasable.

I already tried to implement something like that by using a custom annotation:

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface Environment {

  /**
   * Environment identifier
   */
  @Nonbinding String value() default "";

}

And an according producer:

@Produces
@Environment
public SqlSessionFactory produceEnvironmentFactory(InjectionPoint ip)
  throws Exception {
  Environment environment = ip.getAnnotated().getAnnotation(Environment.class);
  return produceFactory(environment.value());
}

But that did not work due to the fact that you can't provide an @ApplicationScoped producer with a relation to an injection point.

And second problem is that MyBatis CDI creates instances without injection point and therefore I cant reference it.

"WELD-001328: Unable to identify the correct BeanManager." occurs

Hi.
I use MyBatis-CDI 1.0.3 and MyBatis 3.4.6 as JAX-RS application's database layer in Payara 4.1.2 (and Glassfish 4.1.2 and Glassfish 5).

It works fine for a while after deployment, SELECT, UPDATE and so on.
But after 8 requests, when the server is processing the 9th request, below exception occurs. And after that, same exception will occur with any request. After restart the server, that problem will not occur (only with first 8 requests).

Caused by: org.jboss.weld.exceptions.IllegalStateException: WELD-001328: Unable to identify the correct BeanManager. The calling class sun.reflect.GeneratedMethodAccessor81 is not placed in bean archive
	at org.jboss.weld.SimpleCDI.unsatisfiedBeanManager(SimpleCDI.java:88)
	at org.glassfish.weld.GlassFishWeldProvider$GlassFishEnhancedWeld.unsatisfiedBeanManager(GlassFishWeldProvider.java:89)
	at org.jboss.weld.SimpleCDI$ClassNameToBeanManager.findBeanManager(SimpleCDI.java:66)
	at org.jboss.weld.SimpleCDI$ClassNameToBeanManager.apply(SimpleCDI.java:46)
	at org.jboss.weld.SimpleCDI$ClassNameToBeanManager.apply(SimpleCDI.java:39)
	at org.jboss.weld.util.cache.ReentrantMapBackedComputingCache$1.apply(ReentrantMapBackedComputingCache.java:55)
	at org.jboss.weld.util.cache.ReentrantMapBackedComputingCache$1.apply(ReentrantMapBackedComputingCache.java:51)
	at org.jboss.weld.util.cache.ReentrantMapBackedComputingCache.getValue(ReentrantMapBackedComputingCache.java:64)
	at org.jboss.weld.SimpleCDI.getBeanManager(SimpleCDI.java:104)
	at org.jboss.weld.SimpleCDI.getBeanManager(SimpleCDI.java:37)
	... 106 more

I investigated that problem and found the cause.

The exception occurred in CDIUtils.CDI#getBeanManager().

public final class CDIUtils {
  // ...
  private static class CDI {
    // ...
    static BeanManager getBeanManager() {
      if (current != null) {
        try {
          Object cdi = current.invoke(null);
          return (BeanManager) getBeanManager.invoke(cdi);    // <-- HERE
        } catch (Exception ex) {
          throw new RuntimeException(ex);
        }
    }
  }
}

This code uses reflection, and I found that the obtained BeanManager is not same when using below code.

          return javax.enterprise.inject.spi.CDI.current().getBeanManager();

This code uses normal way to obtaining a BeanManager.

So, I tried changing CDIUtils.CDI#getBeanManage() to use normal way. After the change, my application is running fine even after first 8 requests.

I don't know why CDIUtils uses reflection to obtaining a bean manager, but it makes a problem, so could someone please fix it?

Create annotation to rollback exception by default

Nowadays, if I want to rollback when a checked exception happens, I have to set the rollbackFor everytime on the @Transactional annotation.

It would be nice if we could do something similar to EJB transactions, like:

@ApplicationException(
    rollback = true
)
public class BusinessException extends Exception implements Serializable {

Ready for GA Release

Hi @hazendaz , I think we are ready for our first General Availability Release.

  • All passivation/serialization issues were resolved.
  • Docs are up to date
  • Tested with major Containers:
    • Payara 4.1 (Glassfish 4.1)
    • TomEE 7.0.1 Plus
    • Wildfly 10.1.0
    • WAS Liberty with Java EE 7 Full Platform 16.0.0.4
    • Oracle WebLogic 12c
  • There are no more open issues.
  • Clarification about not supporting cdi 1.0 is in the README.

mybatis-cdi-1.0.3 crashes in repeated requests

Hello, I have been testing my jax-rs application using mybatis-cdi-1.0.3, usually crashes in 8th request. When I downgrade to 1.0.2 this one does not crash.

The exception is:

org.jboss.weld.exceptions.IllegalStateException: WELD-001328: Unable to identify the correct BeanManager. The calling class sun.reflect.GeneratedMethodAccessor88 is not placed in bean archive
at org.jboss.weld.SimpleCDI.unsatisfiedBeanManager(SimpleCDI.java:89)
at org.glassfish.weld.GlassFishWeldProvider$GlassFishEnhancedWeld.unsatisfiedBeanManager(GlassFishWeldProvider.java:89)
at org.jboss.weld.SimpleCDI$ClassNameToBeanManager.findBeanManager(SimpleCDI.java:67)
at org.jboss.weld.SimpleCDI$ClassNameToBeanManager.apply(SimpleCDI.java:47)
at org.jboss.weld.SimpleCDI$ClassNameToBeanManager.apply(SimpleCDI.java:40)
at org.jboss.weld.util.cache.ReentrantMapBackedComputingCache.lambda$null$0(ReentrantMapBackedComputingCache.java:55)
at org.jboss.weld.util.WeakLazyValueHolder$1.computeValue(WeakLazyValueHolder.java:35)
at org.jboss.weld.util.WeakLazyValueHolder.get(WeakLazyValueHolder.java:53)
at org.jboss.weld.util.cache.ReentrantMapBackedComputingCache.getValue(ReentrantMapBackedComputingCache.java:72)
at org.jboss.weld.SimpleCDI.getBeanManager(SimpleCDI.java:105)
at org.jboss.weld.SimpleCDI.getBeanManager(SimpleCDI.java:38)
at sun.reflect.GeneratedMethodAccessor88.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.mybatis.cdi.CDIUtils$CDI.getBeanManager(CDIUtils.java:84)
at org.mybatis.cdi.CDIUtils.getBeanManager(CDIUtils.java:108)
at org.mybatis.cdi.CDIUtils.findSqlSessionFactory(CDIUtils.java:134)
at org.mybatis.cdi.SerializableMapperProxy.getMapper(SerializableMapperProxy.java:66)
at org.mybatis.cdi.SerializableMapperProxy.(SerializableMapperProxy.java:53)
at org.mybatis.cdi.MyBatisBean.create(MyBatisBean.java:127)

at org.jboss.weld.contexts.unbound.DependentContextImpl.get(DependentContextImpl.java:70)
at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.get(ContextualInstanceStrategy.java:100)
at org.jboss.weld.bean.ContextualInstance.get(ContextualInstance.java:50)
at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:676)
at org.jboss.weld.manager.BeanManagerImpl.getInjectableReference(BeanManagerImpl.java:776)
at org.jboss.weld.injection.FieldInjectionPoint.inject(FieldInjectionPoint.java:92)
at org.jboss.weld.util.Beans.injectBoundFields(Beans.java:335)
at org.jboss.weld.util.Beans.injectFieldsAndInitializers(Beans.java:346)
at org.jboss.weld.injection.producer.ResourceInjector$1.proceed(ResourceInjector.java:69)
at org.glassfish.weld.services.InjectionServicesImpl.aroundInject(InjectionServicesImpl.java:172)
at org.jboss.weld.injection.InjectionContextImpl.run(InjectionContextImpl.java:46)
at org.jboss.weld.injection.producer.ResourceInjector.inject(ResourceInjector.java:71)
at org.jboss.weld.injection.producer.BasicInjectionTarget.inject(BasicInjectionTarget.java:117)
at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:159)
at org.jboss.weld.contexts.AbstractContext.get(AbstractContext.java:96)
at org.jboss.weld.bean.ContextualInstanceStrategy$DefaultContextualInstanceStrategy.get(ContextualInstanceStrategy.java:100)
at org.jboss.weld.bean.ContextualInstanceStrategy$CachingContextualInstanceStrategy.get(ContextualInstanceStrategy.java:177)
at org.jboss.weld.bean.ContextualInstance.get(ContextualInstance.java:50)
at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:102)
at org.jboss.weld.bean.proxy.ProxyMethodHandler.getInstance(ProxyMethodHandler.java:125)

Thanks.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yaml
  • actions/checkout v4
  • actions/setup-java v4
.github/workflows/codeql.yml
  • actions/checkout v4
  • github/codeql-action v3
  • github/codeql-action v3
  • github/codeql-action v3
.github/workflows/coveralls.yaml
  • actions/checkout v4
  • actions/setup-java v4
.github/workflows/site.yaml
  • actions/checkout v4
  • actions/setup-java v4
  • JamesIves/github-pages-deploy-action v4
.github/workflows/sonar.yaml
  • actions/checkout v4
  • actions/setup-java v4
.github/workflows/sonatype.yaml
  • actions/checkout v4
  • actions/setup-java v4
maven
pom.xml
  • org.mybatis:mybatis-parent 43
  • org.mybatis:mybatis 3.5.16
  • jakarta.annotation:jakarta.annotation-api 3.0.0
  • jakarta.transaction:jakarta.transaction-api 2.0.1
  • jakarta.enterprise:jakarta.enterprise.cdi-api 4.1.0
  • org.jboss.classfilewriter:jboss-classfilewriter 1.3.1.Final
  • org.jboss.weld.se:weld-se-core 5.1.2.Final
  • net.bytebuddy:byte-buddy 1.14.14
  • net.bytebuddy:byte-buddy-agent 1.14.14
  • org.junit.jupiter:junit-jupiter-engine 5.10.2
  • org.mockito:mockito-core 5.11.0
  • org.mockito:mockito-junit-jupiter 5.11.0
  • org.jboss.weld:weld-junit5 4.0.3.Final
  • org.jboss.narayana.jta:narayana-jta 7.0.1.Final
  • org.apache.derby:derby 10.17.1.0
  • org.apache.derby:derbyshared 10.17.1.0
  • org.apache.derby:derbyoptionaltools 10.17.1.0
  • org.slf4j:slf4j-api 2.0.13
  • org.slf4j:slf4j-simple 2.0.13
  • net.bytebuddy:byte-buddy-agent 1.14.14
maven-wrapper
.mvn/wrapper/maven-wrapper.properties
  • maven 3.9.6
  • maven-wrapper 3.3.1

  • Check this box to trigger a request for Renovate to run again on this repository

Site plugin and 'clirr' usage issue with jakarta

Likely due to us moving to jakarta, the release of site fails with '[ERROR] javax.enterprise.util.AnnotationLiteral not found.'. I suspect I could hack a solution together with that but for now just noting it. The site thus is not released along with jakarta at this time.

Permgen Leak in TomEE.

MyBatis CDI causes memory leak in TomEE. After investigation, I have tracked this down to an instance of org.apache.ibatis.executor.ErrorContext that is created during MyBatisBean.create().

To Fix, ErrorContext.instance().reset() needs to be added just before MyBatisBean.create() returns.

As a workaround, I have added ErrorContext.instance().reset(); to my SqlSessionFactoryProvider class after the SqlSessionFactory has been built.

Release 1.0.3

Hi Jeremy (@hazendaz ), Can you please do a new release? There is one important portability enhancement pending to release. Some users will appreciate it.

Thank you!

Migrate from atomikos to narayana

atomikos does not support jakarta at this time. looking at spring boot that dropped that framework support as a result and using narayana instead. we should do the same so we can get jakarta out reliably while keeping both javax and jakarta on same transaction framework.

Breaks with @FlowScoped

It seems like @Inject @Mapper does not work with Beans annotated with JavaServer Faces @FlowScoped Annotation.

We end up with an exception:

[...]
declares a passivating scope but has a non-passivation-capable dependency org.mybatis.cdi.MyBatisBean@56c6c74a
[...]

The @FlowScoped bean implements Serializable, so that is not the problem.

Tested with 1.0.0-beta4-SNAPSHOT and Weld 2.4.0.Final

NullPointerException in stacktrace when deploying an EJB with an Injected Mapper om TomEE

We have a stateless bean part of our deployment and we use MyBatis CDI to inject a Mapper:

@Stateless
public class MyBatisMerchantOrderRepository implements MerchantOrderRepository {
    @Inject
    @Mapper
    private MerchantOrderMapper mapper;

    public MyBatisMerchantOrderRepository() {
    }
}

When we deploy this, we see the following stacktrace, but the application does work as it is supposed to do.

Caused by: java.lang.NullPointerException: null
    at org.mybatis.cdi.SerializableMapperProxy.getMapper(SerializableMapperProxy.java:61)
    at org.mybatis.cdi.SerializableMapperProxy.<init>(SerializableMapperProxy.java:47)
    at org.mybatis.cdi.MyBatisBean.create(MyBatisBean.java:117)
    at org.apache.webbeans.component.third.ThirdpartyBeanImpl.create(ThirdpartyBeanImpl.java:96)
    at org.apache.webbeans.context.DependentContext.getInstance(DependentContext.java:68)
    at org.apache.webbeans.context.AbstractContext.get(AbstractContext.java:125)
    at org.apache.webbeans.container.BeanManagerImpl.getReference(BeanManagerImpl.java:754)
    at org.apache.webbeans.container.BeanManagerImpl.getInjectableReference(BeanManagerImpl.java:628)
    at org.apache.webbeans.inject.AbstractInjectable.inject(AbstractInjectable.java:95)
    at org.apache.webbeans.inject.InjectableField.doInjection(InjectableField.java:65)
    at org.apache.webbeans.portable.InjectionTargetImpl.injectFields(InjectionTargetImpl.java:208)
    at org.apache.webbeans.portable.InjectionTargetImpl.inject(InjectionTargetImpl.java:194)
    at org.apache.webbeans.portable.InjectionTargetImpl.inject(InjectionTargetImpl.java:184)
    at org.apache.openejb.cdi.CdiEjbBean$EjbInjectionTargetImpl.inject(CdiEjbBean.java:388)
    at org.apache.openejb.BeanContext.inject(BeanContext.java:1660)
    at org.apache.openejb.BeanContext.newInstance(BeanContext.java:1489)
    at org.apache.openejb.core.stateless.StatelessInstanceManager.createInstance(StatelessInstanceManager.java:207)
    at org.apache.openejb.core.stateless.StatelessInstanceManager.getInstance(StatelessInstanceManager.java:199)
    at org.apache.openejb.core.stateless.StatelessContainer.invoke(StatelessContainer.java:186)
    at org.apache.openejb.core.ivm.EjbObjectProxyHandler.synchronizedBusinessMethod(EjbObjectProxyHandler.java:317)
    at org.apache.openejb.core.ivm.EjbObjectProxyHandler.businessMethod(EjbObjectProxyHandler.java:312)
    at org.apache.openejb.core.ivm.EjbObjectProxyHandler._invoke(EjbObjectProxyHandler.java:92)
    at org.apache.openejb.core.ivm.BaseEjbProxyHandler.invoke(BaseEjbProxyHandler.java:325)

LocalTransactionInterceptor does not match an interceptor bean (Payara Micro 4.1.1.161.1)

Deploying application on Payara Micro 4.1.1.161.1 gives the following error:

[2016-04-06T15:01:38.510+0200] [Payara 4.1] [SEVERE] [NCLS-CORE-00026] [javax.enterprise.system.core] [tid: _ThreadID=1 _ThreadName=main] [timeMillis: 1459947698510] [levelValue: 1000] [[
  Exception during lifecycle processing
org.glassfish.deployment.common.DeploymentException: CDI deployment failure:WELD-001417: Enabled interceptor class <class>org.mybatis.cdi.LocalTransactionInterceptor</class> in file:/tmp/gfembed3604631096618476727tmp/applications/my-mybatis-app/WEB-INF/classes/META-INF/beans.xml@7 does not match an interceptor bean: the class is not found, or not annotated with @Interceptor and still not registered through a portable extension, or not annotated with @Dependent inside an implicit bean archive
    at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:234)
    at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:131)
    at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:329)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:496)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:487)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:539)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:535)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:534)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:565)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:557)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:360)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:556)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1464)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:109)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1846)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1722)
    at com.sun.enterprise.admin.cli.embeddable.DeployerImpl.deploy(DeployerImpl.java:134)
    at fish.payara.micro.PayaraMicro.deployAll(PayaraMicro.java:931)
    at fish.payara.micro.PayaraMicro.bootStrap(PayaraMicro.java:717)
    at fish.payara.micro.PayaraMicro.main(PayaraMicro.java:105)
Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001417: Enabled interceptor class <class>org.mybatis.cdi.LocalTransactionInterceptor</class> in file:/tmp/gfembed3604631096618476727tmp/applications/my-mybatis-app/WEB-INF/classes/META-INF/beans.xml@7 does not match an interceptor bean: the class is not found, or not annotated with @Interceptor and still not registered through a portable extension, or not annotated with @Dependent inside an implicit bean archive
    at org.jboss.weld.bootstrap.Validator.validateEnabledInterceptorClasses(Validator.java:658)
    at org.jboss.weld.bootstrap.Validator.validateDeployment(Validator.java:481)
    at org.jboss.weld.bootstrap.WeldStartup.validateBeans(WeldStartup.java:443)
    at org.jboss.weld.bootstrap.WeldBootstrap.validateBeans(WeldBootstrap.java:90)
    at org.glassfish.weld.WeldDeployer.event(WeldDeployer.java:225)
    ... 23 more
]]

It looks exactly like a problem described here. Changing bean-discovery-mode in mybatis-cdi beans.xml file to bean-discovery-mode="all" solves the problem.

@Transactional(rollbackOnly = true) is bypassed running tests through TestSuite

I've found a strange behavior using @Transactional(rollbackOnly = true) on method of Test classes used inside a JUnitTestSuite:

I've tried to reproduce this problem inside the mybatis-cdi project forked but I didn't manage to.

So to reproduce the problem I'll refer to my example-project.
I've created two suites:

I expected to run without any error both of them without errors (with an empty test table), but only the first one works fine.
The @Transactional(rollbackOnly = true) on the method UserMapperTestReadWrite.t1_insert is considered only on the first suite, in the second one it is completely bypassed.

Individually each class referred from the suites runs with no errors and failures.

UnsatisfiedResolutionException using aries-cdi 1.1.5 with karaf 4.3.7

ERROR [Aries CCR Thread (-2064156514)] CCR Failure in container activator open on org.apache.aries.cdi.container.internal.container.ContainerBootstrap@6aa6d745
org.apache.webbeans.exception.WebBeansDeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Api type [com.myapp.dao.mapper.UserMapper] is not found with the qualifiers
Qualifiers: [@javax.enterprise.inject.Default()]
for injection into Field Injection Point, field name :  userMapper, Bean Owner : [UserDaoServiceImpl, WebBeansType:MANAGED, Name:null, API Types:[com.myapp.dao.service.impl.UserDaoServiceImpl,java.lang.Object,com.myapp.dao.service.UserDaoService], Qualifiers:[javax.enterprise.inject.Any,org.osgi.service.cdi.annotations.Service]]
        at org.apache.webbeans.config.BeansDeployer.deploy(BeansDeployer.java:335) ~[?:?]
        at org.apache.webbeans.lifecycle.AbstractLifeCycle.bootstrapApplication(AbstractLifeCycle.java:137) ~[?:?]
        at org.apache.webbeans.lifecycle.AbstractLifeCycle.startApplication(AbstractLifeCycle.java:103) ~[?:?]
        at org.apache.aries.cdi.owb.core.OWBCDIContainerInitializer.initialize(OWBCDIContainerInitializer.java:212) ~[?:?]
        at org.apache.aries.cdi.owb.core.OWBCDIContainerInitializer.initialize(OWBCDIContainerInitializer.java:62) ~[?:?]
        at org.apache.aries.cdi.container.internal.container.ContainerBootstrap.open(ContainerBootstrap.java:149) ~[?:?]
        at org.apache.aries.cdi.container.internal.model.ContainerActivator$$Lambda$1206/0x0000000000000000.call(Unknown Source) ~[?:?]
        at org.osgi.util.promise.DeferredPromiseImpl$Submit.run(DeferredPromiseImpl.java:755) ~[?:?]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) [?:?]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) [?:?]
        at java.lang.Thread.run(Thread.java:836) [?:?]
Caused by: javax.enterprise.inject.UnsatisfiedResolutionException: Api type [com.myapp.dao.mapper.UserMapper] is not found with the qualifiers
Qualifiers: [@javax.enterprise.inject.Default()]
for injection into Field Injection Point, field name :  userMapper, Bean Owner : [UserDaoServiceImpl, WebBeansType:MANAGED, Name:null, API Types:[com.myapp.dao.service.impl.UserDaoServiceImpl,java.lang.Object,com.myapp.dao.service.UserDaoService], Qualifiers:[javax.enterprise.inject.Any,org.osgi.service.cdi.annotations.Service]]
        at org.apache.webbeans.util.InjectionExceptionUtil.throwUnsatisfiedResolutionException(InjectionExceptionUtil.java:60) ~[?:?]
        at org.apache.webbeans.container.InjectionResolver.checkInjectionPoint(InjectionResolver.java:252) ~[?:?]
        at org.apache.webbeans.container.BeanManagerImpl.validate(BeanManagerImpl.java:1231) ~[?:?]
        at org.apache.webbeans.util.WebBeansUtil.validate(WebBeansUtil.java:1510) ~[?:?]
        at org.apache.webbeans.config.BeansDeployer.validate(BeansDeployer.java:1153) ~[?:?]
        at org.apache.webbeans.config.BeansDeployer.validateInjectionPoints(BeansDeployer.java:1064) ~[?:?]
        at org.apache.webbeans.config.BeansDeployer.deploy(BeansDeployer.java:306) ~[?:?]
        ... 10 more

The stack is as above

Since we cannot disclose the code of the project, i will post the same sample code that reproduces the same error by tomorrow.

Added

sample code & kar : myapp_sample.zip

I've written a simple sample code as it is used in my existing project.

Environment
Eclipse OpenJ9 VM AdoptOpenJDK (build openj9-0.24.0, JRE 11 Windows 10 amd64-64-Bit 20210120_627 (JIT enabled, AOT enabled)
Apache karaf 4.3.7

Whatever the implementation of usp_get_user, the result only needs to be 1 or 0.

Thank you in advance

UnsatisfiedResolutionException: Api type [] is not found with the qualifiers...

Hi. I'm struggling with MyBatis-CDI injection to other bean. Maybe you have some ideas what I'm doing wrong and what did I miss?
Error I have in my test project:

17-Mar-2019 22:24:29.639 SEVERE [http-nio-8080-exec-4] org.apache.openejb.cdi.OpenEJBLifecycle.startApplication CDI Beans module deployment failed
 org.apache.webbeans.exception.WebBeansDeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Api type [com.mybatis.dao.ServersMapper] is not found with the qualifiers 
Qualifiers: [@javax.enterprise.inject.Default()]
for injection into Field Injection Point, field name :  serversMapper, Bean Owner : [ThirdComp, WebBeansType:MANAGED, Name:thirdComp, API Types:[com.mybatis.ThirdComp,java.lang.Object], Qualifiers:[javax.enterprise.inject.Default,javax.enterprise.inject.Any]]
	at org.apache.webbeans.config.BeansDeployer.deploy(BeansDeployer.java:327)
...

My setup - I'm using mybatis generator to generate my Models, DAO classes and mappers xml's. As my generator works, i assume that there is no problems in that code. Then mybatis and mybatis-cdi configuration:
Maven:

        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-maven-plugin</artifactId>
            <version>1.3.7</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-cdi</artifactId>
            <version>1.0.0-beta7</version>
        </dependency>

MyBatisConfig:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <typeAliases>
        <typeAlias type="com.mybatis.model.Servers" alias="Servers"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="MANAGED"/>
            <dataSource type="JNDI">
                <property name="data_source" value="openejb:Resource/ServersDataSource"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <mapper resource="mybatis/xml/ServersMapper.xml"/>
    </mappers>
</configuration>

I added @Mapper annotation to my ServersMapper.java file (everything else is unchanged from generation)
Then I have

@ApplicationScoped
public class MyBatisDemoResources {

    @Produces
    @ApplicationScoped
    @SessionFactoryProvider
    private SqlSessionFactory produceSqlSessionFactory() {
        try {
            return new SqlSessionFactoryBuilder().build(
                    Resources.getResourceAsStream("MyBatisConfig.xml")
            );
        } catch (IOException e) {
            throw new RuntimeException("MyBatisResources.produceSqlSessionFactory(): ", e);
        }
    }
}

And finally my call from other java class:

@Model
public class SomeClass {
    @Inject
    private ServersMapper serversMapper;
...Other code...

Thanks in advance, hope information I provided is enough to see something : )

missing @Any qualifier on MybatisBean if user provided qualifier is present

Hello,

After reviewing MyBatisBean.java, it appears that the @Any annotation will not be assigned to the bean if a qualifier is present at the injection point.

On line 71:

    if (qualifiers == null || qualifiers.isEmpty()) {
      this.qualifiers = new HashSet<>();
      this.qualifiers.add(new CDIUtils.SerializableDefaultAnnotationLiteral());
      this.qualifiers.add(new CDIUtils.SerializableAnyAnnotationLiteral());
    } else {
      this.qualifiers = qualifiers;
    }

If no qualifiers are found, the @Any annotation will be added. However, if qualifiers are found, the @Any annotation will not be added.

I believe the @Any qualifier should be added regardless.

Thanks.

Dynamically change the SqlSessionFactory of each mapper in each request

Hi.
I am new to CDI and I have a problem that I think is very complex and not fix it.

My system consists of many databases. A database for authentication, and many identical databases ( one for each user). Each user can only access its own database , and you can create databases of users dynamically .

database

The client authenticates to login database and store the schema name in the SessionBean . While the duration of the session for each request we need to determine which database has to access each mapper .

I qualified the mappers and the SqlSessionFactory pointing to login , and pointing to the scheme , but they point to the scheme , the scheme has to be dynamic for each request .

@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface BBDDEsquema {}
@Qualifier
@Retention(RUNTIME)
@Target({TYPE, METHOD, FIELD, PARAMETER})
public @interface BBDDLogin {}
//SqlSessionFactory for login  database (OK)
public class SqlSessionFactoryLoginProvider {

  @Produces
  @ApplicationScoped
  @BBDDLogin
  public SqlSessionFactory produceFactory() throws IOException {
      InputStream inputStream = FacesContext.getCurrentInstance().getExternalContext().
                                                 getResourceAsStream("/WEB-INF/mybatisLogin.xml");    
      SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      return sqlSessionFactory;
  }
}
//SqlSessionFactory of the database user (FAIL). should SqlSessionFactory of gonne one database for each user .
//I think we should keep in a structure similar in the ApplicacionBean
//Map < String, SqlSessionFactory > sqlSessionsFactory, and add  dynamically sqlSessionsFactory the map when the user access for first time
public class SqlSessionFactoryLoginProvider {

  @Produces
  @ApplicationScoped
  @BBDDEsquema
  public SqlSessionFactory produceFactory() throws IOException {
      InputStream inputStream = FacesContext.getCurrentInstance().getExternalContext().
                                               getResourceAsStream("/WEB-INF/mybatisesquema.xml");    
      SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
      return sqlSessionFactory;
  }
}
//(OK)
public class UsuarioLoginService implements Serializable {
    @Inject @Mapper @BBDDLogin private UsuarioMapper usuarioMapper;                   
    public List<Usuario> getUsuarios() {
        return usuarioMapper.selectAll();
    }          
}
//(FAIL)
//The SqlSessionFactory using the mapper should change for each requst
public class AlgoService implements Serializable {
    @Inject @Mapper BBDDEsquema private AlgoMapper algoMapper;               
    public Algo getAlgo() {
        return algoMapper.selectAll();
    }          
}

I apologize for my English ... if you want I 'll explain better in Spanish ;)

Inject bean in a plugin MyBatis has a null value

Hi

I am using CDI (Weld ) in a web application developed in JSF and MyBatis on a Tomcat application server.

When I inject a bean into a plugin of MyBatis, the injected bean always has a null value, instead of injecting the correct instance of the bean.

What am I doing wrong?

Regards

import es.metadata.metaqualitas.web.SessionBean;
import java.io.Serializable;
import java.util.Properties;
import javax.inject.Inject;
import javax.inject.Named;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.log4j.Logger;

@Intercepts({
    @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
    @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
public class ExamplePlugin implements Interceptor, Serializable {

    //log has a ApplicationScope
    @Inject
    private Logger log;

    //sessionBean has a SessionScoped        
    @Inject
    private SessionBean sessionBean;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        //log and sessionBean are always worth null and launch NullPointerException
        log.info(sessionBean.getUsuario());        
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {    
    }
}
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.inject.Inject;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

@ApplicationScoped
@Named
public class LoggerProducer {

    @Produces  
    public Logger produceLogger(InjectionPoint injectionPoint) {        
        return Logger.getLogger(injectionPoint.getMember().getDeclaringClass().getName());  
    }
}

import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named
@SessionScoped
public class SessionBean implements Serializable {

    private String usuario;

    public String getUsuario(){
        return usuario;
    }

    public void setUsuario(String usuario){
        this.usuario = usuario;
    }

    @PostConstruct
    public void init() {
        usuario = "Pedro";
    }
}

CDI injection does not work with Glassfish (Paraya) Server

Hi,

I am trying to use mybatis + mybatis-cdi with Paraya application server so I followed the instruction on this page http://www.mybatis.org/cdi/getting-started.html but it does not work.

This is the runtime exception what I got:

[2017-02-14T22:02:23.715+0100] [Payara 4.1] [INFO] [AS-WEB-GLUE-00172] [javax.enterprise.web] [tid: _ThreadID=101 _ThreadName=admin-listener(6)] [timeMillis: 1487106143715] [levelValue: 800] [[
  Loading application [mybatis-demo-1.0#mybatis-demo-war-1.0.war] at [/demo]]]

[2017-02-14T22:02:23.770+0100] [Payara 4.1] [INFO] [] [javax.enterprise.system.core] [tid: _ThreadID=101 _ThreadName=admin-listener(6)] [timeMillis: 1487106143770] [levelValue: 800] [[
  mybatis-demo-1.0 was successfully deployed in 1,526 milliseconds.]]

[2017-02-14T22:03:00.333+0100] [Payara 4.1] [INFO] [] [javax.enterprise.web] [tid: _ThreadID=25 _ThreadName=http-listener-1(2)] [timeMillis: 1487106180333] [levelValue: 800] [[
  WebModule[null] ServletContext.log():Marking servlet a.b.war.HelloServlet as unavailable]]

[2017-02-14T22:03:00.334+0100] [Payara 4.1] [WARNING] [] [javax.enterprise.web] [tid: _ThreadID=25 _ThreadName=http-listener-1(2)] [timeMillis: 1487106180334] [levelValue: 900] [[
  StandardWrapperValve[a.b.war.HelloServlet]: Allocate exception for servlet a.b.war.HelloServlet
org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type PersonMapper with qualifiers @Default
  at injection point [BackedAnnotatedField] @Inject private a.b.war.HelloServlet.personMapper
  at a.b.war.HelloServlet.personMapper(HelloServlet.java:0)

This is my servlet:

@WebServlet("/servlet")
public class HelloServlet extends HttpServlet {
    @Inject
    private PersonMapper personMapper;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println(personMapper.getPerson(1L).toString());
    }

mapper class:

@Mapper
public interface PersonMapper {
    @Select("SELECT * FROM person WHERE id = #{id}")
    Person getPerson(@Param("id") long id);
}

It seems that MyBatisSQLSessionFactory.getSqlSessionFactory() methos is never called because i cannot see anything in my log file.

My SessionFactory class:

public class MyBatisSQLSessionFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(HelloBean.class);

    @Produces
    @ApplicationScoped
    @SessionFactoryProvider
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        LOGGER.info("MyBatis is initializing...");
        String resource = "mybatis-configuration.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        LOGGER.info("MyBatis has been initialized, SQL Session Factory: {}", sqlSessionFactory.toString());
        return sqlSessionFactory;
    }
}

And the structure of my war:

*.war
│   index.html
│
├───META-INF
│   │   bean.xml
│   │   MANIFEST.MF
│   │
│   └───maven
│         ...
│
└───WEB-INF
    ├───classes
    │   └───a
    │       └───b
    │           └───war
    │               │   HelloServlet.class
    │               │
    │               └───mybatis
    │                   │   MyBatisSQLSessionFactory.class
    │                   │
    │                   └───dao
    │                           PersonMapper.class
    │
    └───lib

Maybe I made a mistake and I forgot something or maybe it is a bug.
Could you please help?

Unsatisfied dependencies with Tomcat and Weld

Hi,

we are running Tomcat 8 with Weld 2.2.8. Dependency Injection works and our code runs fine.

@ApplicationScoped
public class SqlSessionFactoryProducer {

    @Produces @ApplicationScoped
    public SqlSessionFactory produce() {
        try {
            String resource = "de/grasmueck/data/Configuration.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            return sqlSessionFactory;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

All our DAO Classes share the same basic structure.

@RequestScoped
public class MyExamplePojoDAO {

    @Inject
    private SqlSessionFactory sqlSessionFactory;

    public List<MyExamplePojo> select() {
        try (SqlSession session = sqlSessionFactory.openSession()) {
            MyExamplePojoMapper mapper = session.getMapper(MyExamplePojoMapper.class);
            return mapper.select();
        }
    }
}

I am trying to get rid of the boilerplate code with Mybatis-CDI and inject with @Mapper. During deployment I end up with the following exception.

Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type UserTransaction with qualifiers @Default
  at injection point [BackedAnnotatedField] @Inject private transient org.mybatis.cdi.JtaTransactionInterceptor.userTransaction
  at org.mybatis.cdi.JtaTransactionInterceptor.userTransaction(JtaTransactionInterceptor.java:0)

Makes sense because with don't work with JTA Transaction at all. Any chance to make this work? We don't want to work with a full blown application server right now.

Edit
I forgot our Configuration.xml. It is rather simple. We have a single environment with a JDBC Transaction Manager and a POOLED datasource.

Use latest WELD

Since servlet 2.5 is generally now EOL with both tomcat and spring calling it quits, should we go ahead and upgrade to latest weld 2.4.x? The obvious there is that servlet 2.5 support will be dropped.

Unable to use MyBatis-CDI with GlassFish 4 and 4.1

I'm unable to get MyBatis-CDI working with GlassFish 4 and GlassFish 4.1 due to a MybatisCdiConfigurationException exception being thrown with the description "There are no SqlSessionFactory producers properly configured."

The code for the SqlSessionFactory I'm using is as follow:

import javax.annotation.Resource;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.sql.DataSource;

import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

public class SqlSessionFactoryProvider {

    @Resource (lookup="jdbc/MyDatabase")
    DataSource dataSource;

    @Produces
    @ApplicationScoped
    public SqlSessionFactory produceFactory() {
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment environment = new Environment("development",
            transactionFactory, dataSource);
        Configuration configuration = new Configuration(environment);
        configuration.addMapper(ToDoItemMapper.class);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
            .build(configuration);
        return sqlSessionFactory;
    }
}

I've stepped through the code of the MyBatis-CDI module and have found that when the follow line of code in CDIUtils findSqlSessionFactory(...) is executed it fails find any beans that return SqlSessionFactory.class.

beans = beanManager.getBeans(SqlSessionFactory.class, qualifiers.toArray(new Annotation[]{}));

I've tried running my program on GlassFish 4 and 4.1 and they both have the same problem, but it works fine if I run my program on WildFly 8.1. My first thought was that it might be a problem with the version of Weld shipped with Glassfish but it turns out that GlassFish 4.1 is running Weld version 2.2.2 whereas WildFly is running Weld version 2.1.2.

Is there anything I can do in GlassFish, my code or in the MyBatis-CDI module to overcome this problem when running in GlassFish?

NoSuchElementException in test with Arquillian and embedded container

Hi,

i'm trying to run a junit test of a Mybatis sample, with CDI injection, with arquillian and an embedded container (both TomEE and GlassFIsh).

THe sample seems not working, even if the logs show correct behavoir:

Aug 14, 2018 12:01:03 PM org.mybatis.cdi.MybatisExtension processAnnotatedType
INFO: MyBatis CDI Module - Found class with @Mapper-annotation: QueryMapper
Aug 14, 2018 12:01:03 PM org.mybatis.cdi.MybatisExtension processProducer
INFO: MyBatis CDI Module - SqlSessionFactory producer MybatisFactoryProducers.buildFactory
Aug 14, 2018 12:01:03 PM org.mybatis.cdi.MybatisExtension afterBeanDiscovery
INFO: MyBatis CDI Module - Activated
Aug 14, 2018 12:01:03 PM org.mybatis.cdi.MybatisExtension afterBeanDiscovery
INFO: MyBatis CDI Module - Found a bean, which needs a Mapper interface org.example.code.impl.QueryMapper
Aug 14, 2018 12:01:03 PM org.mybatis.cdi.MybatisExtension afterBeanDiscovery
INFO: MyBatis CDI Module - Managed Mapper dependency: org.example.code.impl.QueryMapper, org.example.code.impl.QueryMapper
Aug 14, 2018 12:01:03 PM org.mybatis.cdi.MybatisExtension afterBeanDiscovery
INFO: MyBatis CDI Module - Managed SqlSession: org.apache.ibatis.session.SqlSession, org.apache.ibatis.session.SqlSession
Aug 14, 2018 12:01:03 PM org.apache.webbeans.config.BeansDeployer validateInjectionPoints

Caused by: java.util.NoSuchElementException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1455)
at java.util.HashMap$KeyIterator.next(HashMap.java:1477)
at org.mybatis.cdi.CDIUtils.getRegistry(CDIUtils.java:120)
at org.mybatis.cdi.SerializableMapperProxy.getMapper(SerializableMapperProxy.java:68)
at org.mybatis.cdi.SerializableMapperProxy.(SerializableMapperProxy.java:53)
at org.mybatis.cdi.MyBatisBean.create(MyBatisBean.java:127)

I prepare a sample that replicate the problem:
sample.zip

There is a possibity to resolve the problem and been able to use Mybatis + CDi even in an embedded container?

Thanks!

Injecting a mapper in a servlet filter fails

Hello,

for some reason injecting a mapper in a Servlet Filter fails. The filter is annotated with @webfilter. I can inject other stuff with @Inject. For example a SqlSessionFactory. That works without problems. If I however try to do a @Inject @Mapper it end up with a unsatisfied dependency exception.

I can inject mappers in other JSF beans. So everything with @nAmed and a scope is fine. Only the servlet filter is causing trouble.

Versions:
Servlet API 3.1
Weld 2.3.5.Final
Mybatis 3.4.1
Mybatis-CDI 1.0.0-beta3

Exception:
30-Aug-2016 09:48:29.532 SEVERE [http-nio-8080-exec-7] org.apache.catalina.core.StandardContext.filterStart Exception starting filter de.e2n.gastroapp.perso.servlet.filter.CookieFilter
org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type CookieMapper with qualifiers @default
at injection point [BackedAnnotatedField] @Inject @Mapper private de.e2n.gastroapp.perso.servlet.filter.CookieFilter.cookieMapper
at de.e2n.gastroapp.perso.servlet.filter.CookieFilter.cookieMapper(CookieFilter.java:0)

at org.jboss.weld.bootstrap.Validator.validateInjectionPointForDeploymentProblems(Validator.java:359)
at org.jboss.weld.bootstrap.Validator.validateInjectionPoint(Validator.java:281)
at org.jboss.weld.bootstrap.Validator.validateProducer(Validator.java:417)
at org.jboss.weld.injection.producer.InjectionTargetService.validateProducer(InjectionTargetService.java:36)
at org.jboss.weld.injection.producer.WeldInjectionTargetBuilderImpl.run(WeldInjectionTargetBuilderImpl.java:100)
at org.jboss.weld.injection.producer.WeldInjectionTargetBuilderImpl.build(WeldInjectionTargetBuilderImpl.java:93)
at org.jboss.weld.environment.servlet.inject.AbstractInjector$1.load(AbstractInjector.java:54)
at org.jboss.weld.environment.servlet.inject.AbstractInjector$1.load(AbstractInjector.java:47)
at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3527)
at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2319)
at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2282)
at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2197)
at com.google.common.cache.LocalCache.get(LocalCache.java:3937)
at com.google.common.cache.LocalCache.getOrLoad(LocalCache.java:3941)
at com.google.common.cache.LocalCache$LocalLoadingCache.get(LocalCache.java:4824)
at org.jboss.weld.util.cache.LoadingCacheUtils.getCacheValue(LoadingCacheUtils.java:49)
at org.jboss.weld.util.cache.LoadingCacheUtils.getCastCacheValue(LoadingCacheUtils.java:74)
at org.jboss.weld.environment.servlet.inject.AbstractInjector.inject(AbstractInjector.java:60)
at org.jboss.weld.environment.tomcat.WeldInstanceManager.newInstance(WeldInstanceManager.java:25)
at org.jboss.weld.environment.tomcat.WeldForwardingInstanceManager.newInstance(WeldForwardingInstanceManager.java:72)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:258)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:105)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4561)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5204)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:152)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:724)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:700)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:734)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:596)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:467)
at org.apache.catalina.startup.HostConfig.check(HostConfig.java:1617)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:300)
at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:819)
at com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:801)
at org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1483)
at org.apache.catalina.manager.ManagerServlet.deploy(ManagerServlet.java:904)
at org.apache.catalina.manager.ManagerServlet.doGet(ManagerServlet.java:336)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:632)
at org.apache.catalina.valves.RequestFilterValve.process(RequestFilterValve.java:319)
at org.apache.catalina.valves.RemoteAddrValve.invoke(RemoteAddrValve.java:88)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:1110)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:785)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1425)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

Weld 3.1.7.Final Proxy changes has broken mybatis-cdi support

Update to 3.1.7.Final was reported broken for mybatis-cdi private usage.

This can be demonstrated in our current test set. Simply bump cdi 2.0 support weld up to 3.1.7.Final and run the build with cdi 2.0 profile.

mvn clean install -P"cdi-2.0"

[INFO] Running org.mybatis.cdi.FooServiceTest
[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.107 s <<< FAILURE! - in org.mybatis.cdi.FooServiceTest
[ERROR] org.mybatis.cdi.FooServiceTest Time elapsed: 0.107 s <<< ERROR!

I believe this has to do with the proxy and use of interfaces. I haven't done any further research yet and this could be a bug with weld itself given they broke this on a patch level.

CDI injection does not work in WebSphere Application Server 8.5.5.5

I have a web application with JSF 2.0, mybatis-3.3.0 and mybatis-cdi-1.0.0-beta2. The following two cases does not work running on WebSphere Application Server 8.5.5.5:

@Inject
private SqlSession session;

or

@Inject
@Mapper
private InerfaceXXXMapper mapper;

Eclipse IDE gives me a warning at the @Inject mentioned above:
"No bean is eligible for injection to the injection point [JSR-299 §5.2.1]"

I have a Producer method with ApplicationScoped:

@ApplicationScoped
@produces
public SqlSessionFactory produceFactory() {...}

When I run my application on WebSphere Liberty Profile V8.5 it works since it does not have injection points validation at start up. When the application is accessed the @produces method is called and the factory is loaded with session and mapper proxies.This scenario works fine.

However, when I run my application on the Application Server Full, it uses the OpenWebBeans CDI Container and it tries to validate all injection points at startup, but does not find any class of type "SqlSession" or "InerfaceXXXMapper" being produced. The type produced is "SqlSessionFactory" that holds the proxys for SqlSession and its Mappers registred.

Here is the exception I get at start up:

[7/23/15 16:33:42:226 BRT] 000000b0 WebContainerL I WebContainerLifecycle startApplication OpenWebBeans Container is starting...
[7/23/15 16:33:44:486 BRT] 000000b0 Extension I MyBatis CDI Module - Activated
[7/23/15 16:33:46:196 BRT] 000000b0 BeansDeployer E BeansDeployer deploy
javax.enterprise.inject.UnsatisfiedResolutionException: Api type [org.apache.ibatis.session.SqlSession] is not found with the qualifiers

How can I make it work?

Thanks,

Isaias

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.