注解开发
Mybatis使用的比较多的是配置文件,之后是使用的比较多的是注解开发
面向接口编程
解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵循共同的标准,使得开发变得容易,规范性更好,
-
面向对象系统中,系统各种功能可能是由许许多多的不同对象协作完成,各个对象内部如何实现对系统涉及人员来说不重要
-
对象之间协作是关键,同类之间的通信,模块之间的通信,是在系统设计之初要考虑的,面向接口编程就是按照这种思想来编程
关于接口的理解:
- 接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。
- 接口的本身反应了系统设计人员对系统的抽象理解
- 接口应有两类:
- 对一个 个体的抽象,他可以对应为一个抽象体(abstract class)
- 对一个 个体某一方面的抽象,即形成一个抽象面(interface)
- 一个体有可能有多个抽象面,抽象体与抽象面是有区别的
三个面向区别:
- 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法
- 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现
- 接口设计与非接口设计是针对复用技术而言的,与面向对象、过程不是一个问题,更多的体现就是对系统整体的架构
注解开发
-
在接口上编写注解
-
在mybatis-config.xml设置mapper
-
测试
- 底层原理是注解和反射和动态代理
-
在接口上编写注解
-
public interface UserMapper { @Select("select * from user") List<User>getUsers(); }
- 那个user是idea特有的写法,要连接上了才能这么写
-
将mapper映射到配置文件
-
<!--映射--> <mappers> <mapper class="com.haoyun.dao.UserMapper"/> </mappers>
-
测试
-
@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(); }
-
得出结果password没查出来,因为字段名和JavaBean类中的属性名不一致,暂时只能修改Bean类中的属性名,没法用resultMap,所以注解只能完成一些简单的操作,最好还是通过配置文件来操作
-
总结:
- 通过DeBug功能,可以看到里面的本质是通过反射机制来实现的
- 配置的一些值都会被注入到sqlSession中去
- 能反射到UserMapper就能解析到里面的接口,里面的注解,底层是使用的动态代理来完成注解的工作
Mybatis执行流程
有些过程是内部的
注解实现CRUD
增删改都需要commit提交事务,一般通过SqlSession.commit()提交,还可以在创建SqlSession时就设置自动提交
-
public static SqlSession getSqlSession() { return sqlSessionFactory.openSession(true); }
-
之前创建的工具类,openSession有选项能设置自动提交
-
public interface SqlSessionFactory { SqlSession openSession(); SqlSession openSession(boolean var1);
-
对应的接口,往下查看实现的方法
-
public SqlSession openSession(boolean autoCommit) { return this.openSessionFromDataSource(this.configuration.getDefaultExecutorType(), (TransactionIsolationLevel)null, autoCommit); }
-
boolean 是autoCommit,自动提交,看到这里就行,具体的操作怎么实现还能继续往下探究
-
public interface UserMapper { @Select("select * from user where id =#{id} and name = #{name}") User getUserById(@Param("id") int ida,@Param("name") String namea); }
-
然后再mybatis-config.xml中进行注册
-
<mappers> <mapper class="com.haoyun.dao.UserMapper"/> <!--需要配置的接口多了可以使用通配符--> <mapper class="com.haoyun.dao.*"/> </mappers>
-
使用@Param传递参数,可以不用跟形参名称一致,但是要跟上面注解的名称一致
-
其他的CRUD操作将@Select换成Update、Insert、Delete就行,参数要对上
-
@Test public void Test(){ SqlSession sqlSession = MybatisUtils.getSqlSession(); UserMapper mapper = sqlSession.getMapper(UserMapper.class); User userById = mapper.getUserById(3,"map"); System.out.println(userById); sqlSession.close(); }
-
测试
-
注解还可以和xml配置文件配合来使用
-
接口层通过注解转递参数
-
int deleteById(@Param("deleteParamId") int id);
-
UserMapper.xml通过 #{} 来接收参数
- #{} 和 KaTeX parse error: Expected 'EOF', got '#' at position 10: {} 的区别,#̲可以防止sql注入,不行
-
<mapper namespace="com.haoyun.dao.UserMapper"> <delete id="deleteById" parameterType="int"> delete from user where id = #{deleteParamId} </delete> </mapper>
-
需要注意的是要在主配置文件中注册
-
<mappers> <mapper resource="UserMapper.xml"/> </mappers>