How do I build SqlSessionFactory without XML?

MyBatis comes with a complete configuration classes that allows us to create a configuration object programmatically without using the XML file. In this code snippet you’ll see how to create a SqlSessionFactory object without XML configuration file.

We start by obtaining a javax.sql.DataSource object. Then we create a TransactionFactory object. With these two objects we can then create an Environment object and specify its name, such as development, for development environment. The final step is to create the Configuration object using the previously created environment.

In the Configuration object we can define information such as the type aliases and register all the MyBattis mappers.

How do I create MyBatis mapper?

In this examples you will see how to create or define a data mapper using the MyBatis. The mapper will communicate our application with the underlying databases where the data is stored. MyBatis data mapper is defined as an interface object. We can either use annotations or the xml mapper to define our database query.

In the first steps we will create a domain object, a simple pojo to store our data in the object world. The attributes / fields of our pojo resemble the structure of our records table in the database.

Next we define the mapper interface code, we’ll create a RecordMapper.java file that contains a method to get data from the table. At this time the interface will be as the following:

After create the ResultMapper.java interface we create a RecordMapper.xml file that defines the queries used by our mapper. Here is how it looks like:

To tell MyBatis about our mapper we need to define the mapper inside MyBatis configuration file. We register the mapper inside the <mappers> element of the configuration file.

Finally, we create a simple application to use the data mapper to get record data from the database.

How do I use @Select annotation in MyBatis?

In the previous example How do I create MyBatis mapper? you’ve seen how to use a mapper to get a record from the database. In that example the select query is defined in the mapper xml file. For the same functionality MyBatis also offer a solution to use an annotation for the select query.

In this example we will use the @Select annotation to define the query. To map the query result we can use the @ResultMap annotation where the value passed to this annotation is the result map id that we’ve defined in the mapper xml file.

Let see an example of a mapper interface definition that use an annotation to get a record from database: