mybatis与spring整合1

冷不防 2022-02-04 04:53 331阅读 0赞

整合spring和mybatis的详细步骤

本例所使用的数据库是MySQL,其他数据库换个对应的jdbc就可以了,使用的ide是eclipse

三层架构(3-tier architecture) 通常意义上的三层架构就是将整个业务应用划分为:界面层(View层)(User Interface layer)、业务逻辑层(service层)(Business Logic Layer)、数据访问层(DAO层)(Data access layer)

  1. 导包

    在这里插入图片描述

    需要导入以上的包,也可以使用maven,

  2. 准备数据库

    • 数据库中新建一个表student

      表中有三个字段id(编号)、name(姓名)、和age(年龄)

      1. create table student(
      2. id int primay key,
      3. name varchar(10),
      4. age int
      5. )
    • 先给表中插入一条数据(1,林铠戈,21) 使用cmd的话别忘了commit(提交事务)

      1. insert into student(id,name,age) value(1, '林铠戈', 21)
    • 查看表可以发现数据库已经添加进去了

      在这里插入图片描述

  3. 在com.lin.bean包下新建一个JavaBean-学生类——Student

    1. package com.lin.bean;
    2. public class Student {
    3. //对应学生表中的字段
    4. private int id;
    5. private String name;
    6. private int age;
    7. public int getId() {
    8. return id;
    9. }
    10. public void setId(int id) {
    11. this.id = id;
    12. }
    13. public String getName() {
    14. return name;
    15. }
    16. public void setName(String name) {
    17. this.name = name;
    18. }
    19. public int getAge() {
    20. return age;
    21. }
    22. public void setAge(int age) {
    23. this.age = age;
    24. }
    25. @Override
    26. public String toString() {
    27. return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
    28. }
    29. }
  4. 在src下新建spring的配置文件applicationContext.xml(使用sts或安装了sts插件使用spring更方便,建议去安装一个)

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    3. </beans>
  5. 在src下新建一个properties文件用于保存数据库信息(方便维护)

    账号密码根据自己的电脑修改,驱动等根据自己所使用的数据库修改

    1. url=jdbc:mysql://localhost:3306/mybatis
    2. driver=com.mysql.jdbc.Driver
    3. username=root
    4. password=mysqlMYSQL
  6. 在spring配置文件中引入资源文件(PreferencesPlaceholderConfigurer类)

    PreferencesPlaceholderConfigurer类中有个属性locations,这是一个数组类型,将文件地址放进去就可以了,引入了properties资源文件后,就可以通过**${键}**的方式来获取文件中的值了

    1. <!-- 引入资源文件 -->
    2. <bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    3. <property name="locations">
    4. <array>
    5. <value>classpath:mysqlConfig.properties</value>
    6. </array>
    7. </property>
    8. </bean>
  7. 配置数据源(BasicDataSource类)

    以前只是用mybatis的时候,我们配置数据源是在mybatis配置文件中配置,整合的话,我们将数据源放到spring配置文件中

    BasicDataSource类中的属性有很多,这里就配置url、driver、username、password

    注意:driver在BasicDataSource中的属性是driverClassName

    1. <!-- 配置数据源 -->
    2. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    3. <property name="driverClassName" value="${driver}"></property>
    4. <property name="url" value="${url}"></property>
    5. <property name="username" value="${username}"></property>
    6. <property name="password" value="${password}"></property>
    7. </bean>
  8. 配置SqlSessionFactoryBean

    mybaits-spring.jar为我们提供了SqlSessionFactoryBean,相当于以前的SqlSessionFactory,

    SqlSessionFactoryBean中的dataSource属性用来指定数据源,也就是我们上面配置的数据源,ref引用一下就可以了,他还有一个configLocation属性用来指定mybatis配置文件的位置,这里暂时不配置,等后面添加,记住就行

    1. <!--配置SqlSessionFactoryBean -->
    2. <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
    3. <property name="dataSource" ref="dataSource"></property>
    4. </bean>
  9. 在com.lin.mapper包下新建mapper映射文件和mapper接口

    • 新建StudentMapper接口

      里面有一个queryStudent方法,用来查询学生,根据学号查询学生

      1. package com.lin.mapper;
      2. import com.lin.bean.Student;
      3. public interface StudentMapper {
      4. Student queryStudent(int id);
      5. }
    • 新建mapper映射文件StudentMapper.xml

      注意mapper中的namespace和

      1. <?xml version="1.0" encoding="UTF-8"?>
      2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      3. <mapper namespace="com.lin.mapper.StudentMapper">
      4. <select id="queryStudent" resultType="com.lin.bean.Student">
      5. select * from student where id = #{id}
      6. </select>
      7. </mapper>
  10. 在src下新建mybatis配置文件mybatis.config.xml

    因为数据源在spring中配置完了,所以在mybatis中就不用配置数据源了,但是要引入mapper映射文件

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
    3. <configuration>
    4. <!-- 引入mapper文件 -->
    5. <mappers>
    6. <mapper resource="com/lin/mapper/StudentMapper.xml"/>
    7. </mappers>
    8. </configuration>
  11. 修改spring配置文件

    刚刚在spring中配置SqlSessionFactoryBean的时候说过,他还有一个configLocation属性用来指定mybatis配置文件的位置,现在来配置一下

    1. <!--配置SqlSessionFactoryBean -->
    2. <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
    3. <property name="dataSource" ref="dataSource"></property>
    4. <property name="configLocation" value="classpath:mybatis.config.xml"> </property>
    5. </bean>
  12. 在com.lin.mapper包(三层中的DAO层)新建一个mapper接口的实现类StudentMapperImpl,此类需要实现StudentMapper接口,还需要继承SqlSessionDaoSupport类

    SqlSessionDaoSupport是mybatis提供的用来获取SqlSession的类,该类有一个getSqlSession()方法用来获取SqlSession对象,因此通过继承该类,就可以获得SqlSession,

    实现StudentMapper接口后并重写queryStudent方法

    1. package com.lin.mapper;
    2. import org.apache.ibatis.session.SqlSession;
    3. import org.mybatis.spring.support.SqlSessionDaoSupport;
    4. import com.lin.bean.Student;
    5. public class StudentMapperImpl extends SqlSessionDaoSupport implements StudentMapper{
    6. @Override
    7. public Student queryStudent(int id) {
    8. //获取SqlSession对象
    9. SqlSession session = getSqlSession();
    10. //和mybatis一样,通过动态代理技术使用getMapper获取接口对象
    11. StudentMapper studentMapper = session.getMapper(StudentMapper.class);
    12. Student student = studentMapper.queryStudent(id);
    13. return student;
    14. }
    15. }
  13. 在com.lin.service包下新建一个QueryService接口(三层的中的service层)

    1. package com.lin.service;
    2. import com.lin.bean.Student;
    3. public interface QueryService {
    4. Student queryStudent(int id);
    5. }
  14. 在com.lin.service包下新建一个QueryServiceImpl类,此类实现QueryService接口,并重写接口中方法,进行具体的逻辑处理

    因为是使用spring的方式来进行资源控制,所以就不使用new的方式来创建StudentMapperImpl对象了,通过DI(依赖注入)的方式来创建StudentMapperImpl对象

    1. package com.lin.service;
    2. import com.lin.bean.Student;
    3. import com.lin.mapper.StudentMapperImpl;
    4. public class QueryServiceImpl implements QueryService{
    5. //用于在spring中注入StudentMapperImpl对象
    6. private StudentMapperImpl studentMapperImpl;
    7. public void setStudentMapperImpl(StudentMapperImpl studentMapperImpl) {
    8. this.studentMapperImpl = studentMapperImpl;
    9. }
    10. @Override
    11. public Student queryStudent(int id) {
    12. //通过组装DAO层来实现具体的逻辑
    13. Student student = this.studentMapperImpl.queryStudent(id);
    14. return student;
    15. }
    16. }
  15. 修改spring配置文件,添加各种bean

    • 配置StudentMapperImp类

      注意:StudentMapperImp继承了SqlSessionDaoSupport类,SqlSessionDaoSupport类中有个sqlSessionFactory属性,用于设置sqlSessionFactory,所以我们需要将上面配置的sqlSessionFactoryBean引用到studentMapperImpl中(别忘了)

      1. <!-- 配置DAO层的StudentMapperImpl -->
      2. <bean id="studentMapperImpl" class="com.lin.mapper.StudentMapperImpl">
      3. <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"></property>
      4. </bean>
    • 配置QueryServiceImpl类

      queryServiceImpl依赖于上面的StudentMapperImp类,所以需要ref引用一下上面创建的studentMapperImp

      1. <!-- 配置Service层的QueryServiceImpl -->
      2. <bean id="queryServiceImpl" class="com.lin.service.QueryServiceImpl">
      3. <property name="studentMapperImpl" ref="studentMapperImpl"></property> </bean>
  16. 在com.lin.test包下新建Test类来进行测试

    1. package com.lin.test;
    2. import org.springframework.context.ApplicationContext;
    3. import org.springframework.context.support.ClassPathXmlApplicationContext;
    4. import com.lin.bean.Student;
    5. import com.lin.service.QueryServiceImpl;
    6. public class Test {
    7. public static void main(String[] args) {
    8. ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
    9. QueryServiceImpl queryServiceImpl = (QueryServiceImpl) applicationContext.getBean("queryServiceImpl");
    10. //查询编号为1的学生信息
    11. Student student = queryServiceImpl.queryStudent(1);
    12. System.out.println(student);
    13. }
    14. }
  17. 运行Test类

    在这里插入图片描述

    成功获取到了数据,

一个简单的整合就完成了,这只是一种方法,还有两种方法,后面会写出来

完整的spring配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  3. <!-- 引入资源文件 -->
  4. <bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
  5. <property name="locations">
  6. <array>
  7. <value>classpath:mysqlConfig.properties</value>
  8. </array>
  9. </property>
  10. </bean>
  11. <!-- 配置数据源 -->
  12. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
  13. <property name="driverClassName" value="${driver}"></property>
  14. <property name="url" value="${url}"></property>
  15. <property name="username" value="${username}"></property>
  16. <property name="password" value="${password}"></property>
  17. </bean>
  18. <!--配置SqlSessionFactoryBean -->
  19. <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
  20. <property name="dataSource" ref="dataSource"></property>
  21. <property name="configLocation" value="classpath:mybatis.config.xml"></property>
  22. </bean>
  23. <!-- 配置DAO层的StudentMapperImpl -->
  24. <bean id="studentMapperImpl" class="com.lin.mapper.StudentMapperImpl">
  25. <property name="sqlSessionFactory" ref="sqlSessionFactoryBean"></property>
  26. </bean>
  27. <!-- 配置Service层的QueryServiceImpl -->
  28. <bean id="queryServiceImpl" class="com.lin.service.QueryServiceImpl">
  29. <property name="studentMapperImpl" ref="studentMapperImpl"></property>
  30. </bean>
  31. </beans>

由于步骤较多,所以最好动手一步一步敲,这样才能记得住,光看的话第一次整合是看不出啥的,

本次案例的源代码:微云(谷歌浏览器打开微云会显示空白页面,建议用别的浏览器打开):微云地址

发表评论

表情:
评论列表 (有 0 条评论,331人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Leetcode 题目01

    写在前面: 最近一直在做一些LeetCode的题目,我之前一直是将每道题我的答案和想法以及别人优秀的答案都整合在一起然后上传的GitHub上,但是我发现这样做自己还是很难