MyBatis 3 Annotation Example with @Select, @Insert, @Update and @Delete

By Arvind Rai, March 18, 2015
In this page, we will provide MyBatis 3 annotation example with @Select, @Insert, @Update and @Delete. These annotations are declared in interface on methods for select, insert, update and delete operation. Now this interface will act as Mapper for SQL queries and in this way mapper xml is removed. We need to register mapper interface in MyBatis configuration XML. To map POJO and table columns, MyBatis provides @Results annotation which works same as <resultMap> tag in xml mapper. @Results helps to get query result by @Select annotation. Find the complete example step by step.

Required Software to Run Example

Find the software used to run MyBatis annotation example.
1. Java 7
2. Eclipse
3. Gradle
4. MySQL

Project Structure in Eclipse

Find the print screen of project structure in eclipse which we are using in our example.
MyBatis 3 Annotation Example with @Select,  @Insert, @Update and @Delete

Table Schema

We have created a table to test our queries.
Table: village
CREATE TABLE `village` (
	`id` INT(10) NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(50) NULL DEFAULT NULL,
	`district` VARCHAR(50) NULL DEFAULT NULL,
	PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB; 

Gradle to Resolve JAR Dependencies

Find the gradle file to resolve JAR dependencies of MyBatis and MySQL.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'concretepage'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
    compile 'org.mybatis:mybatis:3.2.8'
    compile 'mysql:mysql-connector-java:5.1.34'
}  

Mapper Interface Using MyBatis Annotation

In MyBatis annotation, we use interface and declare our methods for database query . The required input in query are passed as an argument in method. If we pass POJO as argument, MyBatis will retrieve properties name and its value required for query input.

@Select : We need to provide select query as value.
@Results : Maps column name and POJO property to get result in select query.
@Insert : We need to provide insert query as a value.
@Update : We need to provide update query as a value.
@Delete : We need to provide delete query as a value.

Find the Mapper interface.
VillageMapper.java
package com.concretepage;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
public interface VillageMapper {
	@Results({
          @Result(property = "vid", column = "id"),
          @Result(property = "villageName", column = "name"),
          @Result(property = "district", column = "district")
        })
	@Select("SELECT id, name, district from village WHERE id = #{id}")
	Village selectVillage(int id);
	
	@Insert("INSERT into village(name,district) VALUES(#{villageName}, #{district})")
	void insertVillage(Village village);
	
	@Update("UPDATE village SET name=#{villageName}, district =#{district} WHERE id =#{vid}")
	void updateVillage(Village village);
	
	@Delete("DELETE FROM village WHERE id =#{id}")
	void deleteVillage(int id);
} 

MyBatis Configuration XML: Register Mapper Interface

Find MyBatis configuration xml to configure database environment and mapper interface. In our example we are using MySQL.
mybatis-config.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/concretepage"/>
        <property name="username" value="root"/>
        <property name="password" value=""/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper class="com.concretepage.VillageMapper" />
  </mappers>
</configuration> 

POJO Class used in Example

Find the POJO for the example.
Village.java
package com.concretepage;
public class Village {
	private Integer vid;
	private String villageName;
	private String district;
	public Integer getVid() {
		return vid;
	}
	public void setVid(Integer vid) {
		this.vid = vid;
	}
	public String getVillageName() {
		return villageName;
	}
	public void setVillageName(String villageName) {
		this.villageName = villageName;
	}
	public String getDistrict() {
		return district;
	}
	public void setDistrict(String district) {
		this.district = district;
	}
} 

Utility Class to get SqlSessionFactory

MyBatis utility class to get SqlSessionFactory.
MyBatisUtil.java
package com.concretepage;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class MyBatisUtil {
 	private static SqlSessionFactory sqlSessionFactory;
	static {
		String resource = "mybatis-config.xml";
		InputStream inputStream;
		try {
			inputStream = Resources.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static SqlSessionFactory getSqlSessionFactory(){
		return sqlSessionFactory;
	}
} 

DAO Class: Use SqlSession.getMapper() to get Mapper Instance

Using SqlSession.getMapper(), we retrieve mapper interface implementation by MyBatis and call the methods declared in interface as given below.
VillageMapper mapper = session.getMapper(VillageMapper.class);
Village village = mapper.selectVillage(id); 
Find the DAO class.
VillageDAO.java
package com.concretepage;
import org.apache.ibatis.session.SqlSession;
public class VillageDAO {
	public void save(Village village){
	  SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();	
	  VillageMapper mapper = session.getMapper(VillageMapper.class);
	  mapper.insertVillage(village);
	  session.commit();
	  session.close();
	}
	public void update(Village village){
	  SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();	
	  VillageMapper mapper = session.getMapper(VillageMapper.class);
	  mapper.updateVillage(village);
	  session.commit();
	  session.close();
	}
	public void delete(Integer id){
	  SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();	
	  VillageMapper mapper = session.getMapper(VillageMapper.class);
	  mapper.deleteVillage(id);
	  session.commit();
	  session.close();
	}
	public Village getData(Integer id) {
	  SqlSession session = MyBatisUtil.getSqlSessionFactory().openSession();	
	  VillageMapper mapper = session.getMapper(VillageMapper.class);
	  Village village = mapper.selectVillage(id);
	  session.close();
	  return village;
	}
} 

Main Class To Test Demo Application

Now we will test our application. Here in this class we call all the methods of DAO class to test our application.
RunMybatis.java
package com.concretepage;
public class RunMybatis {
	public static void main(String[] args) {
	  VillageDAO villageDAO = new VillageDAO();	
	  //insert	
	  Village village = new Village();
	  village.setVillageName("Crossing Republic");
	  village.setDistrict("Ghaziabad");
	  villageDAO.save(village);
	  System.out.println("---Data saved---");
	  //update
	  village = new Village();
	  village.setVid(1);
	  village.setVillageName("Dhananjaypur");
	  village.setDistrict("Varanasi");
	  villageDAO.update(village);
	  System.out.println("---Data updated---");
	  //select
	  village = villageDAO.getData(1);
	  System.out.println("id:"+village.getVid()+", Name:"+village.getVillageName()+", District:"+village.getDistrict());
	  //delete
	  villageDAO.delete(1);
	  System.out.println("---Data deleted---");
	}
} 
Find the output.
---Data saved---
---Data updated---
id:1, Name:Dhananjaypur, District:Varanasi
---Data deleted--- 
I am done now. Enjoy learning!

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us