mybatis
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 theenvironment
element contains the environment configuration for transaction management and connection pooling. ThedataSource
element configures the source of JDBC Connection objects using the standard JDBC DataSource interface. Themappers
element contains theEmployeeMapper.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 inEmployeeMapper.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 themybatis.conf.xml
file as a Reader object, using thegetResourceAsReader(java.lang.String resource)
API method oforg.apache.ibatis.io.Resources
. - Create a new
org.apache.ibatis.session.SqlSessionFactoryBuilder
and use itsbuild(Reader reader)
API method to create aorg.apache.ibatis.session.SqlSessionFactory
, and with itsopenSession()
API method open a neworg.apache.ibatis.session.SqlSession
. - Use the
getMapper(Class<T> type)
API method of SqlSession to get theEmployeeMapper
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.
Hello, good tutorial, how can you configure the mybatis log for log4j2.xml?