Questions tagged [mybatis]

MyBatis is a framework for mapping objects to relational databases with an emphasis on high performance and simplicity. XML descriptors or annotations couple the objects to SQL statements or stored procedures.

MyBatis is a framework for mapping objects (Java and .NET) to relational databases with an emphasis on simplicity. The objects are coupled with SQL statements and/or stored procedures using XML descriptor files. Unlike ORM frameworks MyBatis does not map Java objects to database tables but methods to SQL statements.

MyBatis is lightweight and quite easy to use since the only parts involved are the own objects, XML and SQL. It also integrates with the Spring framework.

Example mapping file:

<sqlMap namespace="CUSTOMER">
    <resultMap class="com.example.Customer" id="CustomerMapping">
        <result column="CUSTOMER_ID" property="customerId" jdbcType="DECIMAL" />
        <result column="NAME" property="name" jdbcType="VARCHAR" />
    </resultMap>
    <select id="CUSTOMER.selectByPrimaryKey" parameterClass="java.lang.Long" resultMap="CustomerMapping">
        <![CDATA[  
          SELECT customer_id,
                 name
            FROM customer
           WHERE customer_id = #id:DECIMAL#
        ]]>
    </select>
</sqlMap>

Simple usage:

Interface:

package org.mybatis.example;

public interface BlogMapper {
  @Select("select * from Blog where id = #{id}")
  Blog selectBlog(int id);
}

Using interface:

BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);

SQL statements and mappings can also be externalized to an XML file like this:

<?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="org.mybatis.example.BlogMapper">
  <select id="selectBlog" parameterType="int" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>

Spring integration:

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
</bean>

<bean id="blogMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />
  <property name="mapperInterface" value="org.mybatis.example.BlogMapper" />
</bean>

<bean id="blogService" class="org.mybatis.example.BlogServiceImpl">
  <property name="blogMapper" ref="blogMapper" />
</bean>

In code you just use blogMapper interface:

public class BlogServiceImpl implements BlogService {

  private BlogMapper blogMapper;

  public void setBlogMapper(BlogMapper blogMapper) {
      this.blogMapper = blogMapper;
  }

  public void doSomethingWithABlog(int blogId) {
      Blog blog = blogMapper.selectBlog(blogId);
      // ...
  }
}

Resources

3418 questions
42
votes
9 answers

MyBatis, how to get the auto generated key of an insert? [MySql]

how can I get the generated key of an insert with MyBatis? I read many pages about this question but I'm still blocked, could anyone help me, please? This is my code: The table: ID_ERROR long primary key DATE timestamp TYPE varchar MESSAGE…
user2572526
  • 1,219
  • 2
  • 17
  • 35
40
votes
2 answers

Difference between ibatis and mybatis

What is the difference between iBatis and myBatis? Where can i find a perfect example of those ? Please suggest. I went through Google and could not find any links for this question.
abhay sachu
  • 433
  • 2
  • 5
  • 6
38
votes
6 answers

Can I pass a List as a parameter to a MyBatis mapper?

I'm trying to define a simple @Select annotation in MyBatis to get a collection of objects based on criteria defined by an IN clause. The SQL looks something like: SELECT * FROM employees WHERE employeeID IN (1, 2, 3); The list is generated…
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
37
votes
8 answers

Replacing a full ORM (JPA/Hibernate) by a lighter solution : Recommended patterns for load/save?

I'm developing a new Java web application and I'm exploring new ways (new for me!) to persist the data. I mostly have experience with JPA & Hibernate but, except for simple cases, I think this kind of full ORM can become quite complex. Plus, I don't…
electrotype
  • 8,342
  • 11
  • 59
  • 96
33
votes
9 answers

How to use Annotations with iBatis (myBatis) for an IN query?

We'd like to use only annotations with MyBatis; we're really trying to avoid xml. We're trying to use an "IN" clause: @Select("SELECT * FROM blog WHERE id IN (#{ids})") List selectBlogs(int[] ids); MyBatis doesn't seem able to pick out the…
dirtyvagabond
  • 1,881
  • 2
  • 19
  • 23
32
votes
4 answers

How to pass an Integer Array to IN clause in MyBatis

There is a query in my Mybatis containing an IN clause which is basically a set of Id's ( Integers) I am now stuck on how can I pass an Integer array to this IN clause so that it pulls up the proper records.Tried by passing a String containing the…
Vivek
  • 2,091
  • 11
  • 46
  • 61
31
votes
1 answer

Return HashMap in mybatis and use it as ModelAttribute in spring MVC

I want to display list of categories in my Jsp page using spring mvc @modelAttribute. In my mapper.xml file is In my Mapper.java class I have…
Harry
  • 4,705
  • 17
  • 73
  • 101
29
votes
3 answers

When to use $ vs #?

I am confused about using $ vs #. I didn't found any guides for this. I used them as name = #{name}, name like '%${word}%', order by name ${orderAs},where name = #{word} Sometimes , these are work fine but at the sometimes , parameters aren't…
Cataclysm
  • 7,592
  • 21
  • 74
  • 123
28
votes
3 answers

How to configure Spring to make JPA (Hibernate) and JDBC (JdbcTemplate or MyBatis) share the same transaction

I have a single dataSource, I use Spring 3.0.3, Hibernate 3.5.1 as JPA provider and I use MyBatis 3.0.2 for some queries and my app runs on Tomcat 6. I have a HibernateDAO and a MyBatisDAO, when I call both from the same method which is annotated…
tewe
  • 2,707
  • 3
  • 22
  • 18
23
votes
4 answers

Java 8 LocalDate mapping with mybatis

I am using java.time.LocalDate (Java 8) to represent some of the member fields in a Java class. class Test{ private LocalDate startDate; private LocalDate endDate; //other fields //getters and setters } I am also using…
Scrooge McD
  • 335
  • 1
  • 3
  • 12
23
votes
3 answers

How can I pass multiple parameters and use them?

Hi I'm new to myBatis. I'm using MyBatis and Spring with mybatis-spring. How can I pass two different types of objects as parameters, and how can I use their properties in query? UPDATE SOME…
Jin Kwon
  • 20,295
  • 14
  • 115
  • 184
23
votes
6 answers

Returning values from MyBatis mapped methods

I have a Java project that uses MyBatis to access a PostgreSQL database. PostgreSQL allows to return fields of a newly created row after an INSERT statement, and I want to use it to return the auto-generated BIGSERIAL id of newly created records.…
Idan Arye
  • 12,402
  • 5
  • 49
  • 68
22
votes
11 answers

(How) can I use "LIKE" in SQL queries with MyBatis safely and DB-agnostic?

In MyBatis, you mark the places where parameters should be inserted into your SQL like so: SELECT * FROM Person WHERE id = #{id} This syntax activates proper escaping etc to avoid, among other things, SQL injection attacks. If you have trusted…
Hanno Fietz
  • 30,799
  • 47
  • 148
  • 234
22
votes
3 answers

MyBatis/iBatis - reusable sql fragments in a separate SQL Map file?

I would like to put sql fragments used by several of my SQL Map XML files in a separate file. At the moment, the elements with these fragments are in one of the mappers together with other elements like