Develop CRUD with Mybatis annotation and crud with mybatis Annotation
The previous article demonstrated how to use XML to operate Mybatis to implement CRUD, but writing a large number of XML configuration files is very annoying. Therefore
Mybatis also provides annotation-based configuration methods. The following example shows how to use interfaces and annotations to implement CRUD.
First, create an interface.
package com.bird.mybatis.bean;import java.util.List;import org.apache.ibatis.annotations.Delete;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Update;public interface UserMapper {@Insert("insert into users(name, age) values(#{name}, #{age})")public int add(Users user);@Delete("delete from users where id = #{id}")public int deleteById(int id);@Update("update users set name = #{name}, age = #{age} where id = #{id}")public int update(Users user);@Select("select * from users where id = #{id}")public Users getUserById(int id);@Select("select * from users")public List<Users> getAllUsers();}
Then do not forget to register this class in the conf. xml configuration file.
<mappers><mapper resource="com/bird/mybatis/bean/userMapper.xml" /><mapper class="com.bird.mybatis.bean.UserMapper"/></mappers>
The following describes how to use this class.
@ Testpublic void testAdd2 () {SqlSession openSession = factory. openSession (); UserMapper mapper = openSession. getMapper (UserMapper. class); mapper. add (new Users (-1, "doll", 99); openSession. commit (); openSession. close ();}
How does mybatis implement simultaneous input of object parameters and annotation parameters?
The User-Defined Object is also annotated with @ param.
When used in mapper. xml, # {object alias. attribute name}, such as # {user. id}
Note that if @ pram annotation is used, parameterType is not added to mapper. xml.
Public List <UserExtension> selectAllUsers (@ Param ("user") UserExtension user, @ Param ("begin") int begin, @ Param ("end") int end );
How can I manage transactions without using spring only for mybatis? It is better to have code with comments
Manage the entire process by yourself