Quantcast

Container managed transaction + DAO pattern

classic Classic list List threaded Threaded
8 messages Options
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Container managed transaction + DAO pattern

Arnold Somogyi
Hi,

I am planning to remove Eclipselink JPA from my project and use MyBatis instead of it but I stuck how to use CDI + Container managed Transaction.

At first my plan was to use mybatis-cdi but it is nor released yet :( I read some documentation about how to create SQLSessionFactory and as I understand I have the following two ways.

1st way with static singleton class:

public class SQLSessionFactory {
    private static final SqlSessionFactory SESSION_FACTORY;

static {
try {
Reader reader = Resources.getResourceAsReader("mybatis-configuration.xml");
SESSION_FACTORY = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e){
throw new RuntimeException("Fatal Error. Cause: " + e.getMessage(), e);
}
}

public static SqlSessionFactory getSqlSessionFactory() {
return SESSION_FACTORY;
}
}

Usage:
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class DaoImpl implements Dao {
    private SqlSessionFactory sqlSessionFactory;
 
    @PostConstruct
     public void init() {
        sqlSessionFactory = SQLSessionFactory.getSqlSessionFactory();
    }
 
    @Override
    public List<...> getEmployees() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ...
        sqlSession.close();
        return results;
    }
}


2nd way with mybatis-cdi:
public class SQLSessionFactory {
    @Produces
@ApplicationScoped
@SessionFactoryProvider
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-configuration.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory;
}
}

Usage:
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class DaoImpl implements Dao {
   // HERE I DO NOT KNOW WHAT TO INJECT :(
}


My questions are:
  1. Can I use mybatis-cdi beta6 in production or you recommend me to use the 1st solution?
  2. Could you please give me an an example how to use in practice the mybatis-cdi? I do not know what I need to inject in my 2nd scenario.
  3. It is not clear how to use container managed transaction in a application server environment. I do not want to do sqlSessionFactory.openSession().commit() manually. If I want to use container managed transactions then what I need to inject to my dao implemantation? In that case it seems for me that I need to inject something different then SqlSessionFactory object.

Thank you.

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Container managed transaction + DAO pattern

Frank Martínez
Hi Arnold,
I am using mybatis-cdi in production since beta1. no problem so far.

Anyway, mybatis-cdi is a so small project, it just wires some things, but it is not rocket science, and you have full access to its source code, so it is very low risk.

Cheers,
Frank.

On Tue, Feb 14, 2017 at 7:04 AM, Arnold Somogyi <[hidden email]> wrote:
Hi,

I am planning to remove Eclipselink JPA from my project and use MyBatis instead of it but I stuck how to use CDI + Container managed Transaction.

At first my plan was to use mybatis-cdi but it is nor released yet :( I read some documentation about how to create SQLSessionFactory and as I understand I have the following two ways.

1st way with static singleton class:

public class SQLSessionFactory {
    private static final SqlSessionFactory SESSION_FACTORY;

static {
try {
Reader reader = Resources.getResourceAsReader("mybatis-configuration.xml");
SESSION_FACTORY = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e){
throw new RuntimeException("Fatal Error. Cause: " + e.getMessage(), e);
}
}

public static SqlSessionFactory getSqlSessionFactory() {
return SESSION_FACTORY;
}
}

Usage:
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class DaoImpl implements Dao {
    private SqlSessionFactory sqlSessionFactory;
 
    @PostConstruct
     public void init() {
        sqlSessionFactory = SQLSessionFactory.getSqlSessionFactory();
    }
 
    @Override
    public List<...> getEmployees() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        ...
        sqlSession.close();
        return results;
    }
}


2nd way with mybatis-cdi:
public class SQLSessionFactory {
    @Produces
@ApplicationScoped
@SessionFactoryProvider
public SqlSessionFactory getSqlSessionFactory() throws IOException {
String resource = "mybatis-configuration.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
return sqlSessionFactory;
}
}

Usage:
@Stateless
@TransactionManagement(TransactionManagementType.CONTAINER)
public class DaoImpl implements Dao {
   // HERE I DO NOT KNOW WHAT TO INJECT :(
}


My questions are:
  1. Can I use mybatis-cdi beta6 in production or you recommend me to use the 1st solution?
  2. Could you please give me an an example how to use in practice the mybatis-cdi? I do not know what I need to inject in my 2nd scenario.
  3. It is not clear how to use container managed transaction in a application server environment. I do not want to do sqlSessionFactory.openSession().commit() manually. If I want to use container managed transactions then what I need to inject to my dao implemantation? In that case it seems for me that I need to inject something different then SqlSessionFactory object.

Thank you.

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.



--
Frank D. Martínez M.

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Container managed transaction + DAO pattern

Arnold Somogyi
Hi Frank,

Thank you for the reply.
I followed the instruction on this page http://www.mybatis.org/cdi/getting-started.html but it does not work for me.

This is the runtime exception what I got with Glassfish (actually it is a Payara) application server:

    [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 test 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());
        }

My mapper class:

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

It seems that MyBatisSQLSessionFactory.getSqlSessionFactory() method 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(MyBatisSQLSessionFactory.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 finally 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... Could you please check it?

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Container managed transaction + DAO pattern

Frank Martínez
Hi Arnold,
There is a working example tested with Payara here: https://github.com/mnesarco/mybatis-cdi-samples

On Tue, Feb 14, 2017 at 4:48 PM, Arnold Somogyi <[hidden email]> wrote:
Hi Frank,

Thank you for the reply.
I followed the instruction on this page http://www.mybatis.org/cdi/getting-started.html but it does not work for me.

This is the runtime exception what I got with Glassfish (actually it is a Payara) application server:

    [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 test 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());
        }

My mapper class:

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

It seems that MyBatisSQLSessionFactory.getSqlSessionFactory() method 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(MyBatisSQLSessionFactory.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 finally 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... Could you please check it?

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.



--
Frank D. Martínez M.

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Container managed transaction + DAO pattern

Arnold Somogyi
Hi Frank,

Thank you for the link.
It seems something wrong here or I made a mistake. You can check this topic: issues 52



On Wednesday, February 15, 2017 at 6:05:36 AM UTC+1, Frank Martinez wrote:
Hi Arnold,
There is a working example tested with Payara here: <a href="https://github.com/mnesarco/mybatis-cdi-samples" target="_blank" rel="nofollow" onmousedown="this.href=&#39;https://www.google.com/url?q\x3dhttps%3A%2F%2Fgithub.com%2Fmnesarco%2Fmybatis-cdi-samples\x26sa\x3dD\x26sntz\x3d1\x26usg\x3dAFQjCNGoshziKegePPMTA42gdtbeKllchw&#39;;return true;" onclick="this.href=&#39;https://www.google.com/url?q\x3dhttps%3A%2F%2Fgithub.com%2Fmnesarco%2Fmybatis-cdi-samples\x26sa\x3dD\x26sntz\x3d1\x26usg\x3dAFQjCNGoshziKegePPMTA42gdtbeKllchw&#39;;return true;">https://github.com/mnesarco/mybatis-cdi-samples

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Container managed transaction + DAO pattern

Arnold Somogyi
It is solved, someone has found a workaround.
You can see details here: https://github.com/mybatis/cdi/issues/52

Thank you for your help.



On Thursday, February 16, 2017 at 2:59:09 AM UTC+1, Arnold Somogyi wrote:
Hi Frank,

Thank you for the link.
It seems something wrong here or I made a mistake. You can check this topic: <a href="https://github.com/mybatis/cdi/issues/52" target="_blank" rel="nofollow" onmousedown="this.href=&#39;https://www.google.com/url?q\x3dhttps%3A%2F%2Fgithub.com%2Fmybatis%2Fcdi%2Fissues%2F52\x26sa\x3dD\x26sntz\x3d1\x26usg\x3dAFQjCNEMiC4JszEF1mbXHCbufJSx7Mqq_Q&#39;;return true;" onclick="this.href=&#39;https://www.google.com/url?q\x3dhttps%3A%2F%2Fgithub.com%2Fmybatis%2Fcdi%2Fissues%2F52\x26sa\x3dD\x26sntz\x3d1\x26usg\x3dAFQjCNEMiC4JszEF1mbXHCbufJSx7Mqq_Q&#39;;return true;">issues 52

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Container managed transaction + DAO pattern

Frank Martínez


El 16/02/2017 3:06 AM, "Arnold Somogyi" <[hidden email]> escribió:
It is solved, someone has found a workaround.

:D I am mnesarco.

Cheers,
Frank.

You can see details here: https://github.com/mybatis/cdi/issues/52

Thank you for your help.



On Thursday, February 16, 2017 at 2:59:09 AM UTC+1, Arnold Somogyi wrote:
Hi Frank,

Thank you for the link.
It seems something wrong here or I made a mistake. You can check this topic: issues 52

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.
Reply | Threaded
Open this post in threaded view
|  
Report Content as Inappropriate

Re: Container managed transaction + DAO pattern

RickFlist
unsub

On Thu, Feb 16, 2017 at 7:26 PM, Frank Martínez <[hidden email]> wrote:


El 16/02/2017 3:06 AM, "Arnold Somogyi" <[hidden email]> escribió:
It is solved, someone has found a workaround.

:D I am mnesarco.

Cheers,
Frank.

You can see details here: https://github.com/mybatis/cdi/issues/52

Thank you for your help.



On Thursday, February 16, 2017 at 2:59:09 AM UTC+1, Arnold Somogyi wrote:
Hi Frank,

Thank you for the link.
It seems something wrong here or I made a mistake. You can check this topic: issues 52

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "mybatis-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to [hidden email].
For more options, visit https://groups.google.com/d/optout.
Loading...