mybatis与spring整合1

整合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(年龄)

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

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

      在这里插入图片描述

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

    package com.lin.bean;
    
    public class Student {
        //对应学生表中的字段
    	private int id;
    	private String name;
    	private int age;
    
    	public int getId() {
    		return id;
    	}
    
    	public void setId(int id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public int getAge() {
    		return age;
    	}
    
    	public void setAge(int age) {
    		this.age = age;
    	}
    
    	@Override
    	public String toString() {
    		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
    	}
    	
    }
    
    
  4. 在src下新建spring的配置文件applicationContext.xml(使用sts或安装了sts插件使用spring更方便,建议去安装一个)

    <?xml version="1.0" encoding="UTF-8"?>
    <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">
    </beans>
    
  5. 在src下新建一个properties文件用于保存数据库信息(方便维护)

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

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

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

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

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

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

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

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

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

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

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

    • 新建StudentMapper接口

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

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

      注意mapper中的namespace和

      <?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">
      <mapper namespace="com.lin.mapper.StudentMapper">
      	<select id="queryStudent" resultType="com.lin.bean.Student">
      		select * from student where id = #{id}
      	</select>
      </mapper>
      
  10. 在src下新建mybatis配置文件mybatis.config.xml

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

    <?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>
    	<!-- 引入mapper文件 -->
    	<mappers>
    		<mapper resource="com/lin/mapper/StudentMapper.xml"/>
    	</mappers>
    </configuration>
    
  11. 修改spring配置文件

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

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

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

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

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

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

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

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

    • 配置StudentMapperImp类

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

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

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

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

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

    在这里插入图片描述

    成功获取到了数据,

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

完整的spring配置文件

<?xml version="1.0" encoding="UTF-8"?>
<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">
	<!-- 引入资源文件 -->
	<bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
		<property name="locations">
			<array>
				<value>classpath:mysqlConfig.properties</value>
			</array>
		</property>
	</bean>
	<!-- 配置数据源 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${driver}"></property>
		<property name="url" value="${url}"></property>
		<property name="username" value="${username}"></property>
		<property name="password" value="${password}"></property>
	</bean>
	<!--配置SqlSessionFactoryBean -->
	<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource"></property>
		<property name="configLocation" value="classpath:mybatis.config.xml"></property>
	</bean>
	
	<!-- 配置DAO层的StudentMapperImpl -->
	<bean id="studentMapperImpl" class="com.lin.mapper.StudentMapperImpl">
		<property name="sqlSessionFactory" ref="sqlSessionFactoryBean"></property>
	</bean>
	
	<!-- 配置Service层的QueryServiceImpl -->
	<bean id="queryServiceImpl" class="com.lin.service.QueryServiceImpl">
		<property name="studentMapperImpl" ref="studentMapperImpl"></property>
	</bean>
</beans>

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

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值