Home » Enterprise Java » mybatis » How use @Select MyBatis annotation

About Ilias Tsagklis

Ilias Tsagklis
Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.

How use @Select MyBatis annotation

In this example we shall show you how to use @Select MyBatis annotation. 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 use the simple @Select annotation to make a simple select you can follow the steps below as described in the example:

  • Create a class, Employee.java with variables and their getters and setters, as shown below:
     
     

    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). In this method the @Select("SELECT * FROM employee WHERE id = #{id}") annotation is used, with the SQL expression. We also use the @ResultMap annotation, so that the result of the select will be set to the specified result mapper.
    package com.javacodegeeks.snippets.enterprise;
    
    import org.apache.ibatis.annotations.ResultMap;
    import org.apache.ibatis.annotations.Select;
    
    public interface EmployeeMapper {
    
    	@Select("SELECT * FROM employee WHERE id = #{id}")
    	@ResultMap("employeeResultMap")
    	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.
    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">
    	<resultMap id="employeeResultMap" type="com.javacodegeeks.snippets.enterprise.Employee">
    
      <result column="name" property="name"/>
    
      <result column="surname" property="surname"/>
    
      <result column="title" property="title"/>
        </resultMap>
    </mapper>
    
  • Create a main application (HowUseSelectMyBatisAnnotation here). 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 HowUseSelectMyBatisAnnotation {
    	
    	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 use @Select MyBatis annotation in Java.

0 0 vote
Article Rating

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 our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Subscribe
Notify of
guest
The comment form collects your name, email and content to allow us keep track of the comments placed on the website. Please read and accept our website Terms and Privacy Policy to post a comment.

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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Jose Poma
Jose Poma
1 year ago

Hello, good tutorial, how can you configure the mybatis log for log4j2.xml?

1
0
Would love your thoughts, please comment.x
()
x