mybatis

How create MyBatis mapper

This is an example of how to  create a mapper using MyBatis framework. MyBatis is a first class persistence framework with support for custom SQL, stored procedures and advanced mappings. It can use simple XML or Annotations for configuration and map primitives, Map interfaces and Java POJOs (Plain Old Java Objects) to database records. In order to create a MyBatis mapper you can follow the steps below as described in the example:

  • Create a class, Employee.java with variables and their getters and setters.
     
     
     

    package com.javacodegeeks.snippets.enterprise;
    
    import java.util.Date;
    
    public class Employee {
    	
    	private Long id;
        private String name;
        private String surname;
        private String title;
        private Date created;
        
    	public Long getId() {
    		return id;
    	}
    	public void setId(Long id) {
    		this.id = id;
    	}
    	
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	
    	public String getSurname() {
    		return surname;
    	}
    	public void setSurname(String surname) {
    		this.surname = surname;
    	}
    	
    	public String getTitle() {
    		return title;
    	}
    	public void setTitle(String title) {
    		this.title = title;
    	}
    	
    	public Date getCreated() {
    		return created;
    	}
    	public void setCreated(Date created) {
    		this.created = created;
    	}
    
    }
    
  • Create the mapper interface, EmployeeMapper.java that has a method Employee findById(long id).
    package com.javacodegeeks.snippets.enterprise;
    
    public interface EmployeeMapper {
    	
    	Employee findById(long id);
    
    }
    
    
  • Define the configuration file. Here, the mybatis.conf.xml file contains settings for the core of the MyBatis system, including a DataSource for acquiring database Connection instances, as well as a TransactionManager for determining how transactions should be scoped and controlled. The body of the environment element contains the environment configuration for transaction management and connection pooling. The dataSource element configures the source of JDBC Connection objects using the standard JDBC DataSource interface. The mappers element contains the EmployeeMapper.xml that contains the mapping definition. 
    mybatis.conf.xml

    <?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>
    
    	<environments default="development">
    		<environment id="development">
    			<transactionManager type="JDBC" />
    			<dataSource type="POOLED">
    				<property name="driver" value="com.mysql.jdbc.Driver" />
    				<property name="url" value="jdbc:mysql://localhost/companydb" />
    				<property name="username" value="jcg" />
    				<property name="password" value="jcg" />
    			</dataSource>
    		</environment>
    	</environments>
    	
    	<mappers>
    		<mapper resource="EmployeeMapper.xml" />
    	</mappers>
    	
    </configuration>
    
  • Define the mapper. The EmployeeMapper.java class is defined in EmployeeMapper.xml. The SQL query is writen here and mapped to an object.
    EmployeeMapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    
    <!DOCTYPE mapper
    PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    
    <mapper namespace="com.javacodegeeks.snippets.enterprise.EmployeeMapper">
    
        <select id="findById" parameterType="long" resultType="com.javacodegeeks.snippets.enterprise.Employee">SELECT id, name, surname, title, created FROM employee WHERE id = #{id}  </select>
    </mapper>
    
  • Create a main application. Get the mybatis.conf.xml file as a Reader object, using the getResourceAsReader(java.lang.String resource) API method of org.apache.ibatis.io.Resources.
  • Create a new org.apache.ibatis.session.SqlSessionFactoryBuilder and use its build(Reader reader) API method to create a org.apache.ibatis.session.SqlSessionFactory, and with its openSession() API method open a new org.apache.ibatis.session.SqlSession.
  • Use the getMapper(Class<T> type) API method of SqlSession to get the EmployeeMapper and invoke its method to get the result.
    package com.javacodegeeks.snippets.enterprise;
    
    import java.io.Reader;
    
    import org.apache.ibatis.io.Resources;
    import org.apache.ibatis.session.SqlSession;
    import org.apache.ibatis.session.SqlSessionFactory;
    import org.apache.ibatis.session.SqlSessionFactoryBuilder;
    
    public class HowCreateMyBatisMapper {
    	
    	private static final String conf = "mybatis.conf.xml";
    	
    	public static void main(String[] args) throws Exception {
    		
    		Reader reader = Resources.getResourceAsReader(conf);
    		
    		SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
    		
    		SqlSessionFactory sessionFactory = builder.build(reader);
    		
    		SqlSession session = sessionFactory.openSession();
    		
    		long id = 1;
    		
    		EmployeeMapper mapper = session.getMapper(EmployeeMapper.class);
    		Employee employee = mapper.findById(id);
    		
    		System.out.println(employee.getId() + " - " + employee.getName() +
    				" - " + employee.getSurname());
    		
    	}
    
    }
    

Output:

1 - Jack - Thomson

 
This was an example of how to create a MyBatis mapper in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button