Boris Lam

About Boris Lam

Boris is an experienced Java developer with in Hong Kong. His expertise is in Java EE technology, object-oriented application development, and the use of open source frameworks (e.g. Spring , Apache MyFaces). In recent years, he is primarily involved in framework development and architectural design in serveral Government related software development projects.

Lightweight Web Application Framework: PrimeFaces (JSF) + Guice + MyBatis (Part 2)

In this part, I will continue to demonstrate the integration of JSF, Guice and MyBatis. DBCP connection pool and MYSQL database is used in persistence layer. Take a look at Part 1.

Integrate Google Guice with MyBatis

In the previous post, we have created a ServletContextListener. Now, we just bind the BasicDataSourceProvider and JdbcTransactionFactory in the contextInitialized method.

package org.borislam;

import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;
import org.apache.log4j.xml.DOMConfigurator;
import org.borislam.mapper.StaffMapper;
import org.borislam.service.SimpleService;
import org.borislam.service.impl.SimpleServiceImpl;
import org.mybatis.guice.MyBatisModule;
import org.mybatis.guice.datasource.dbcp.BasicDataSourceProvider;
import org.mybatis.guice.datasource.helper.JdbcHelper;


public class GuiceContextListener implements ServletContextListener {

   public void contextDestroyed(ServletContextEvent servletContextEvent) {
     ServletContext servletContext = servletContextEvent.getServletContext();

   public void contextInitialized(ServletContextEvent servletContextEvent) {
     Injector injector = Guice.createInjector(
       new MyBatisModule() {
        protected void initialize() {         

         Names.bindProperties(binder(), createServerProperties());

         //add singleton service class

         //add MyBatis Service class

     ServletContext servletContext = servletContextEvent.getServletContext();
     servletContext.setAttribute(Injector.class.getName(), injector);


   protected static Properties createServerProperties() {
         Properties myBatisProperties = new Properties();

         myBatisProperties.setProperty('', 'localhost');
         myBatisProperties.setProperty('JDBC.port', '3306');
         myBatisProperties.setProperty('JDBC.schema', 'ttcoach');

         myBatisProperties.setProperty('JDBC.username', 'root');
         myBatisProperties.setProperty('JDBC.password', '');
         myBatisProperties.setProperty('JDBC.autoCommit', 'false');
         return myBatisProperties;


Prepare your MyBatis mapper class and model class

package org.borislam.model;

public class Staff {
 private String code;
 private String name;
 private String sex;
 private String tel;
 public String getCode() {
  return code;
 public void setCode(String code) {
  this.code = code;
 public String getName() {
  return name;
 public void setName(String name) { = name;
 public String getSex() {
  return sex;
 public void setSex(String sex) { = sex;

 public String getTel() {
  return tel;
 public void setTel(String tel) { = tel;


package org.borislam.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.borislam.model.Staff;

public interface StaffMapper {

     * Returns the list of all Freelancer instances from the database.
     * @return the list of all Freelancer instances from the database.
    @Results(value = {
        @Result(property='code', column='code'),
        @Result(property='name', column='name'),
        @Result(property='sex', column='sex'),
        @Result(property='tel', column='tel')
    List<Staff> selectAll();

     * Returns a Freelancer instance from the database.
     * @param id primary key value used for lookup.
     * @return A Freelancer instance with a primary key value equals to pk. null if there is no matching row.
    @Results(value = {
            @Result(property='code', column='code'),
            @Result(property='name', column='name'),
            @Result(property='sex', column='sex'),
            @Result(property='tel', column='tel')
    Staff selectByCode(String code);

Prepare your Service Class

package org.borislam.service;

public interface SimpleService {
 public void doSimpleThing();

package org.borislam.service.impl;

import java.util.List;

import org.borislam.mapper.StaffMapper;
import org.borislam.model.Staff;
import org.borislam.service.SimpleService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class SimpleServiceImpl implements SimpleService {

 private StaffMapper staffMapper;

 Logger logger = LoggerFactory.getLogger(this.getClass());

 public void setStaffMapper(StaffMapper staffMapper) {
  this.staffMapper = staffMapper;

 public void doSimpleThing() {
  List<Staff> staffList = staffMapper.selectAll();
  logger.debug('size 1: ' + staffList.size());

  Staff staff = staffMapper.selectByCode('c001');
  logger.debug('Code1 : ' + staff.getCode());
  logger.debug('Name 1: ' + staff.getName());;

Prepare your JSF Backing Bean and xhtml page

package org.borislam.view;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.inject.Inject;
import org.borislam.service.SimpleService;
import org.borislam.service.TestService;

public class TestBean extends BasePageBean {

 private SimpleService sService;

 public void setsService(SimpleService sService) {
  this.sService = sService;

 public String doTest(){
  System.out.println('test 1 inside backing bean...');
  return '';

 public String doTest2(){
  System.out.println('test 2 inside backing bean...');
  return '';


<html xmlns=''
.ui-widget, .ui-widget .ui-widget {
font-size: 80% !important;
 <h:outputText value='#{msg['website.title']}' />
    <p:calendar id='popupButtonCal' showOn='button' />
    <p:commandButton value='TEST2' action='#{testBean.doTest}'/>

That’s done! You can now ready to write your JSF application based on this framework.
Reference: Lightweight Web Application Framework: PrimeFaces (JSF) + Guice + MyBatis (PART 2) from our JCG partner Boris Lam at the Programming Peacefully blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply

seven × = 21

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below: