MyBatis is a widely used light-weight ORM tool. MyBatis can use XML or Java Annotations for configure all Jdbc, sql mapping and POJOs to database.
In this tutorial, I will create a simple program to demonstrate how to setup a java project with MyBatis.
Create a MyBaits project
The tools used:
- Create database:
-
Create a maven project and setup the dependencies:
-
Create the jdbc.properties in main/resources
-
Setup the mybatis configuration file mybatis-config.xml in main/resources
Note: we have set a alias which map UserInfo.java to User.
-
Setup the UserMapper.xml in main/resources/mappers (You can use Java Annotation instead of XML as well)
-
Create the model Object UserInfo.class in main/java/com/learnBatis
-
Create the mapper interface UserMapper.interface in main/java/com/learnBatis
-
Now, we need setup the connection to the db by creating the MyBatisUtil.class in com.learnBatis package
-
We need use the mapper to query the db, so we create a UserService.class in com.learnBatis
Use MyBatis SQLMapper
Here, we has completed all the tasks needed for setting up MyBatis to our psql database. To test our program, we can simply write a Main.class:
The output will be like: