Compilation of already published Articles/Ideas/Problems-Solutions which I faced or came across over the period of time. Largely a place for me to document it as note-to-self. Nothing serious. :)
As a first step of this tutorial, Spring MVC 3 CRUD example with MyBatis 3, we will define a MyBatis service that will help us to perform CRUD operation on database.
We have a domain class for User and a database table to store the User information on database. We will use xml configuration model for our example to define SQL commands that will perform CRUD operation.
//setter and getter have been omitted to make the code short
16
17
@Override
18
publicString toString() {
19
return"User [name="+ name + ", standard="+ standard + ", age="+ age
20
+ ", sex="+ sex + "]";
21
}
22
}
We have five properties in our domain class called User for which have to provide database services.
Our Database Table
Following is our database table:
1
CREATETABLE`user` (
2
`id` varchar(36) NOTNULL,
3
`name` varchar(45) DEFAULTNULL,
4
`standard` varchar(45) DEFAULTNULL,
5
`age` varchar(45) DEFAULTNULL,
6
`sex` varchar(45) DEFAULTNULL,
7
PRIMARYKEY(`id`)
8
) ENGINE=InnoDB DEFAULTCHARSET=utf8
Creating interface for CRUD operations
For defining the CRUD database operation using MyBatis 3, we have to specify the methods that will be used to perform CRUD operation. Following is the interface for our example:
01
packagecom.raistudies.persistence;
02
03
importjava.util.List;
04
05
importcom.raistudies.domain.User;
06
07
publicinterfaceUserService {
08
09
publicvoidsaveUser(User user);
10
publicvoidupdateUser(User user);
11
publicvoiddeleteUser(String id);
12
publicList getAllUser();
13
}
We have four methods here to perform operations create,update , delete and get from database.
The mapping file will contain element to define the SQL statement for the services. Here the property “namespace” defines the interface for which this mapping file has been defined.
tag defines that the operation is of type insert. The value of “id” property specifies the function name for which the SQL statement is been defined. Here it is “saveUser“. The property “parameterType” defines the parameter of the method is of which type. We have used alias for the class User here. The alias will be configured in MyBatis Configuration file later. Then, we have to define the SQL Statement. #{id} defines that the property “id” of class User will be passed as a parameter to the SQL query.
tag is used to specify the mapping between the User class and user table. id of is a unique name to the mapping definition. Under this tag, we define the different properties and which column is bounded to which property.
1 comment:
Nice Article. Good explanation to integrate spring and MyBatis
Post a Comment