您的位置:首頁技術文章
文章詳情頁

MyBatis使用注解開發實現過程詳解

瀏覽:42日期:2023-10-24 10:35:04

使用注解開發

1、面向接口編程

面向接口編程的根本原因:解耦,可擴展,提高復用,分層開發中、上層不用管具體的實現,大家都遵守共同的標準,使得開發變得容易,規范性好

2、使用注解開發

注解在接口上實現

@Select(value = 'select * from user')List<User> getUsers();

需要在核心配置文件中綁定接口

<!--綁定接口--><mappers> <mapper /></mappers>

測試

public class UserMapperTest { @Test public void test(){ SqlSession sqlSession = MyBatisUtils.getSqlSession(); //底層主要應用反射 UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> users = mapper.getUsers(); for (User user : users) { System.out.println(user); } sqlSession.close(); }}

本質:反射機制實現

底層:動態代理

3、CRUD

我們可以在工具類創建的時候實現自動提交事務

public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(true);}

編寫接口,增加注解

public interface UserMapper { @Select(value = 'select * from user') List<User> getUsers(); //方法存在多個參數,所有的參數前面必須加上@Param注解 @Select('select * from user where id = #{id} or name = #{name}') User getUserByID(@Param('id')int id,@Param('name')String name); @Insert('insert into user(id,name,pwd) values (#{id},#{name},#{password})') int addUser(User user); @Update('update user set name = #{name},pwd = #{password} where id = #{id}') int updateUser(User user); @Delete('delete from user where id = #{uid}') int deleteUser(@Param('uid') int id);}

測試類

【注意:我們必須要將接口注冊綁定到我們的核心配置文件中】

關于@Param()注解

基本類型的參數或者String類型,需要加上 引用類型不需要加 如果只有一個基本類型的化,可以忽略,但是建議都加上 我們在SQL中引用的就是我們這里的@Param()中設定的屬性名

#{} ${}區別

{}是預編譯處理,${}是字符串替換 mybatis在處理#{}時,會將sql中的#{}替換為?號,調用PreparedStatement的set方法來賦值;mybatis在處理${}時,就是把${}替換成變量的值 使用#{}可以有效的防止SQL注入,提高系統安全性

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Mybatis 數據庫
相關文章:
国产综合久久一区二区三区