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 an annotation-based configuration method. The following example shows how to use interfaces and annotations to implement CRUD. First, create an interface. Packagecom. bird. mybatis. bean; importj
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 an annotation-based configuration method. The following example shows how to use interfaces and annotations to implement CRUD. First, create an interface. Package com. bird. mybatis. bean; import j
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
getAllUsers();}
Then do not forget to register this class in the conf. xml configuration file.
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 ();}