Implementing mapper classes

MyBatis uses mapper classes (actually, interfaces) to define the methods that will map SQL queries to Java objects. These are almost the equivalent of the repository classes we have developed so far. However, it makes sense to use MyBatis terminology when using it. Also, as we'll see later, we need to add transaction or session management code around the calls to the mapper class, but let's start with the mapper class. If you were observant, the mybatis-config.xml file defined a mapper class in the mappers section. Go back and have a look at it. The following is the definition of such a mapper:

public interface MessageMapper {

@Select("SELECT id, content FROM messages")
List<Message> findAll();

@Insert("INSERT INTO messages(content) VALUES (#{content})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
void save(Message message);

}

As you can see, MessageMapper is an interface. You don't have to implement this interface; MyBatis will provide the implementation for you at runtime. We have defined two methods: one to return a List of Messages, and another to save a Message. Notice the @Select and @Insert annotations. These are used to define the SQL that will run when these methods are called. Also, notice how you can pass values from the arguments to the SQL query. The save method accepts a Message instance. In the SQL query defined by the @Insert annotation, we use #{content}  to pass the value of the Message.content property to the query. You could have passed a String with the value too. In that case, you can use the name of the parameter directly. However, we want MyBatis to set the value of the id property after the row has been inserted. This value is autogenerated in the database, so we have to use the @Options annotation to configure this behavior.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset