mybatis增删改查接口的写法
2020-10-14Java进阶
mybatis增删改查接口的写法,包含了Insert、Update、Delete、Select的注解映射
public interface UserMapper {
//查一个
@Select("SELECT * FROM student WHERE id = #{id}")
User selectUser(int id);
//查多个
@Select("SELECT * FROM student")
List<User> selectAll();
//差多个-返回map
@MapKey("id")
@Select("SELECT * FROM student")
Map<Integer, User> selectUsers();
//查多个-懒加载
@Select("SELECT * FROM student")
Cursor<User> selectUsers2();
//增加-通过属性
@Insert("INSERT INTO student (name,age) VALUES(#{name},#{age})")
int insertUser(@Param("name") String name,@Param("age")int age);
//增加-通过对象
@Insert("INSERT INTO student (name,age) VALUES(#{name},#{age})")
int insertUser2(User user);
//改-通过对象
@Update("UPDATE student set name=#{name},age=#{age} where id=#{id}")
int updateUser(User user);
//改-通过属性
@Update("UPDATE student set name=#{name},age=#{age} where id=#{id}")
int updateUser2(@Param("name")String name,@Param("age")int age,@Param("id")long id);
//改-通过属性
@Update("UPDATE student set age=#{age} where age <= #{ageCondition}")
int updateUserAgeToEighteen(@Param("age")int age,@Param("ageCondition")int ageCondition);
//删-通过属性
@Delete("DELETE FROM student WHERE id = #{id}")
int deleteUser(long id);
//删-通过对象
@Delete("DELETE FROM student WHERE id = #{id}")
int deleteUser2(User user);
}
映射规则为:接口中的方法需要对象sqlSession中的对应增删改查方法,接口方法的返回值需一致。
下面的示例展示了一些方法签名以及它们是如何映射到 SqlSession 上的。
public interface AuthorMapper {
// (Author) selectOne("selectAuthor",5);
Author selectAuthor(int id);
// (List<Author>) selectList(“selectAuthors”)
List<Author> selectAuthors();
// (Map<Integer,Author>) selectMap("selectAuthors", "id")
@MapKey("id")
Map<Integer, Author> selectAuthors();
// insert("insertAuthor", author)
int insertAuthor(Author author);
// updateAuthor("updateAuthor", author)
int updateAuthor(Author author);
// delete("deleteAuthor",5)
int deleteAuthor(int id);
}
上例中sqlSession.selectOne 等于接口的 AuthorMapper.selectAuthor
sqlSession.selectList等于接口的 AuthorMapper.selectAuthors
等等。
在增加,修改和删除时,需要将sqlSession的事务设置为自动提交openSession(true),更改才会生效。
很赞哦! ()