最近开始了SpringBoot相关知识的学习,作为为目前比较流行、用的比较广的Spring框架,是每一个Java学习者及从业者都会接触到一个知识点。作为Spring框架项目,肯定少不了与数据库持久层的整合。我们在学习Java初始就被灌输SSM框架(Spring、SpringMVC、Mybatis),我们大概也只是知道Mybatis是与数据库打交道的,但这也只是名词上的理解。
Mybatis具体是什么?
MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
。。。。。。
这里我就不废话介绍了,详细的看官方文档地址:https://mybatis.org/mybatis-3/zh/index.html
到后来开始完整的学习Mybatis、到Spring、SpringMVC、再到SpringBoot都有它的身影,它的使用及配置越来越简单方便,可能出现这种情况,学到SpringBoot整合Mybatis发现,为什么要这么操作?为什么要写这个注解?为什么要添加扫描包配置?那么这篇文章就是将开始学习Mybatis到现在SpringBoot整合Mybatis的知识串起来,加深印象增加理解。
下面是我往期关于Mybatis知识点的博客,有兴趣的可以看一下。
首先我也是作为Java的一名初学者,下面文章也是按照从JDBC、Mybatis、Spring、SpringMVC、再到SpringBoot的思路编写,也是我自己的学习路线中Mybatis由繁到简的过程。大致分为五个阶段,可能后面几个阶段内容可以合并为一个阶段,我为了体现Mybatis使用的方便简化,从而作为一个阶段。也可以帮助那些直接学习SpringBoot的同学理解整合Mybatis的递进过程。如果其中有错误之处,也烦请各位大佬给予指正!感谢!
我们在学习Mybatis之前,我们使用JDBC即数据库连接驱动进行数据库连接操作。
其大致操作步骤:
com.mysql.cj.jdbc.Driver
DriverManager.getConnection(url, userName, passWord)
connection.createStatement()
statement.executeQuery(sql)
public static void main(String[] args) throws ClassNotFoundException, SQLException { // 1.加载驱动(固定写法) Class.forName("com.mysql.cj.jdbc.Driver");// 注意加载新的驱动,旧的弃用了 // 2.用户信息和url String url = "jdbc:mysql://localhost:3306/school?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSl=true";// 注意添加时区参数 String userName = "root"; String passWord = "970628"; // 3.连接成功,数据库对象 Connection connection = DriverManager.getConnection(url, userName, passWord); // 4.执行sql的对象 Statement statement = connection.createStatement(); // 5.执行sql String sql= "SELECT * FROM student"; ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()){ System.out.println("name="+resultSet.getObject("name")); } // 6.释放链接 resultSet.close(); statement.close(); connection.close(); }
JDBC的一些问题:
Mybatis对jdbc的操作数据库的过程进行封装,使开发者只需要关注 SQL 本身,而不需要花费精力去处理例如注册驱动、创建connection、创建statement、手动设置参数、结果集检索等jdbc繁杂的过程代码。
其大致步骤:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <!--核心配置文件--> <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/school?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=True"/> <property name="username" value="root"/> <property name="password" value="970628"/> </dataSource> </environment> </environments> </configuration>
public class MybatisUtils { private static SqlSessionFactory sqlSessionFactory; static { try { // 获取sqlSessionFactory对象 String resource="mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); } catch (IOException e) { e.printStackTrace(); } } // 既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。 // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法。你可以通过 SqlSession 实例来直接执行已映射的 SQL 语句 public static SqlSession getSqlSession(){ return sqlSessionFactory.openSession(); } }
public interface StudentMapper { // 查询全部学生 List<Student> getStudentList(); // 根据id查询学生 Student getStudentById(int id); // 插入一个学生 int addUser(Student student); } <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <!--这里的namespace要与dao下的Mapper名称一一对应--> <mapper namespace="com.tioxy.dao.StudentMapper"> <!--id对应的是Mapper接口中对应的方法--> <!--resultType是SQL语句的返回值--> <!--parameterType参数类型--> <select id="getStudentList" resultType="com.tioxy.pojo.Student"> select * from school.student </select> <select id="getStudentById" resultType="com.tioxy.pojo.Student" parameterType="int"> select * from school.student where id = #{id} </select> <insert id="addUser" parameterType="com.tioxy.pojo.Student" > insert into school.student (id,name,password,sex,birthd,address,email) values (#{id},#{name},#{password},#{sex},#{birthd},#{address},#{email}); </insert> </mapper>
<!--每一个Mapper.xml文件都需要在mybatis核心配置文件中注册--> <mappers> <mapper resource="com/tioxy/dao/StudentMapper.xml"/> </mappers>
sqlSession.getMapper()
public void test(){ // 第一步,获取sqlSession对象 SqlSession sqlSession= MybatisUtils.getSqlSession(); try { // 方式一,getMapper StudentMapper mapper = sqlSession.getMapper(StudentMapper.class); List<Student> studentList = mapper.getStudentList(); for (Student student : studentList) { System.out.println(student); } }catch (Exception e){ e.printStackTrace(); }finally { // 关闭sqlSession sqlSession.close(); } }
MyBatis-Spring 会帮助你将 MyBatis 代码无缝地整合到 Spring 中。它将允许 MyBatis 参与到 Spring 的事务管理之中,创建映射器 mapper 和 SqlSession 并注入到 bean 中,以及将 Mybatis 的异常转换为 Spring 的 DataAccessException。最终,可以做到应用代码不依赖于 MyBatis,Spring 或 MyBatis-Spring。
大致步骤如下:
mybatis-spring
DriverManagerDataSource
<!--DataSources:使用Spring的数据源替换Mybatis的配置 这里使用Spring提供的JDBC --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/school?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=True"/> <property name="username" value="root"/> <property name="password" value="970628"/> </bean>
SqlSessionFactoryBean
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> </bean>
SqlSessionDaoSupport
import com.tioxy.pojo.User; import org.mybatis.spring.support.SqlSessionDaoSupport; import java.util.List; public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{ @Override public List<User> selectUser() { return getSqlSession().getMapper(UserMapper.class).selectUser(); } }
<bean id="userMapper2" class="com.tioxy.mapper.UserMapperImpl2"> <property name="sqlSessionFactory" ref="sqlSessionFactory"/> </bean>
ApplicationContext
public void selectUserTest() throws IOException { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserMapper userMapper = context.getBean("userMapper2", UserMapper.class); for (User user : userMapper.selectUser()) { System.out.println(user); } }
其中第5步,原理是内置使用了 SqlSessionTemplate ,SqlSessionTemplate 是 MyBatis-Spring 的核心。作为 SqlSession 的一个实现,这意味着可以使用它无缝代替你代码中已经在使用的 SqlSession。SqlSessionTemplate 是线程安全的,可以被多个 DAO 或映射器所共享使用。构建 SqlSessionTemplate 是 Spring学习之Spring与Mybatis的两种整合方式 中的第一种整合方式,本文章使用第二种方式。
SqlSessionTemplate
总的来说,就是 Mybatis 的操作被Spring接管,通过一个个Spring Bean来实现持久层操作。
其实有的小伙伴在这一阶段已经开始使用注解方式进行Mybatis操作,我这里为了说明Mybatis的整个演进过程,使用配置方式说明
在这一阶段与第三阶段中使用Mybatis并没有很大的差别,前四步与第三阶段相同,其最大的改进是在Spring注册bean MapperScannerConfigurer,其最大的作用是通过反射的方式自动的帮我们构造Mapper的实现类,省去我们手动编写。
MapperScannerConfigurer
<!--配置dao接口扫描包,动态的实现Dao接口可以注入到Spring容器中--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!--注入 sqlSessionFactory--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!--要扫描的包--> <property name="basePackage" value="com.tioxy.mapper"/> </bean>
接下来就是通过Service层调用来实现具体的业务。
所以这一阶段与阶段三并没有太大的差别与提升。可能有的小伙伴说,这一阶段使用阶段三也是可以的,的确如此。其实对于我来说,可能这一阶段使用了 MapperScannerConfigurer,算作上一阶段的简化,所以拿出作为阶段四,同理,我将使用注解的方式作为第四阶段的简化,所以放作下一阶段五。
在这一阶段使用注解进行开发,大大简化了各项配置,使得更加专注于业务及Sql的操作,避免了大量繁琐的配置。
大致步骤:
mybatis-spring-boot-starter
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency>
spring: datasource: username: root password: 970628 url: jdbc:mysql://localhost:3306/school?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver
# 整合Mybatis mybatis: # 别名 type-aliases-package: com.tioxy.pojo # 原来dao与mapper.xml在同一路径,现在不在同一路径需要设置下面的参数,目的就是告诉*.xml文件的路径 mapper-locations: classpath:mybatis/mapper/*.xml
在前阶段的构建 SqlSessionFactoryBean 以及 SqlSession 全都由Spring帮我们实现,所以这里我们省去了这几项配置,只需在Mapper接口上添加@Mapper 注解,表示了这是一个 mybatis 的mapper 类,由Spring帮我们设置,而且也省去了阶段四种使用 MapperScannerConfigurer 来创建Mapper对应的接口
SqlSession
@Mapper
这里我使用Mapper.xml编写SQL语句,也可以使用注解方式,两种方式都可以,看个人喜好。我选择xml文件的原因是编写SQL语句灵活、扩展性好
如果使用注解方式编写Sql,则不需要Mapper.xml文件,也不要设置Mapper.xml的扫描配置,直接在接口的方法中使用 @Select、@Insert等注解
@Select
@Insert
@Mapper @Repository public interface UserMapper { /** * 查询所有的用户 * @return */ @Select("select * from User") List<User> queryUserList(); }
这里面 @Repository,是告诉Spring,这是一个Spring组件,类似于 @Controller、@Service一样
@Repository
@Controller
@Service
如果不想在每个方法中都加上 @Mapper 注解,可以直接在SpringBoot主启动类上添加 @MapperScan注解
@MapperScan
@SpringBootApplication @MapperScan("com.tioxy.mapper") public class SpringBootMybatisApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMybatisApplication.class, args); } }
@Autowired
通过一个个阶段的演进,从一开始JDBC,手动创建数据库连接,创建 statement 执行Sql,这种方式,频繁打开关闭数据库,且Sql与Java代码耦合度高,修改Sql需要修改Java代码,很不方便,于是通过Mybatis进行封装,在单独的xml文件种统一编写Sql,大大简化了操作。Mybatis在不同阶段随着Spring的演进,也在逐渐简化了各种繁琐的配置,以及到最后的SpringBoot中,不再需要手动创建 SqlSessionFactoryBean、SqlSession 以及Mapper的实现类,通过注解操作,使得更加专注于业务及Sql的编写。当然在Java的体系中,持久化框架不只是Mybatis,还有Hibernate、TopLink、dbutils、Spring Data,其大致原理相似,这就需要根据实际开发及个人习惯进行选择。
statement
编写不易,转载请注明出处 如有不当之处,感谢指正!
原文链接:https://www.cnblogs.com/tioxy/p/13417711.html