Spring整合Mybatis

spring中整合mybatis

一 先添加spring框架

1.创建一个maven项目
2.在pom.xml中添加spring jar包
<!-- Spring -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>4.1.3.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-core</artifactId>
  <version>4.1.3.RELEASE</version>
</dependency>

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-beans</artifactId>
  <version>4.1.3.RELEASE</version>
</dependency>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context-support</artifactId>
  <version>4.1.3.RELEASE</version>
</dependency>

  

3.创建基本mvc结构

pojo层:

Items类

package com.test.pojo;

import java.util.Date;

public class Items {
       private int id;
       private String name;
       private float price;
       private String detail;
       private String pic;
       private Date createtime;

    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 float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }

    public Date getCreatetime() {
        return createtime;
    }

    public void setCreatetime(Date createtime) {
        this.createtime = createtime;
    }

    @Override
    public String toString() {
        return "Items{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", detail='" + detail + '\'' +
                ", pic='" + pic + '\'' +
                ", createtime=" + createtime +
                '}';
    }
}

  

dao层

接口 IItemsDao

package com.test.dao;

import com.test.pojo.Items;

import java.util.List;

public interface IItemsDao {


    public List<Items> selectItems();
}

  

实现类 ItemsDao

package com.test.dao.impl;

import com.test.dao.IItemsDao;
import com.test.mapper.ItemsMapper;
import com.test.pojo.Items;

import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.List;


public class ItemsDao implements IItemsDao {

    public ItemsDao()
    {

    }
    public List<Items> selectItems()
    {
          return null;
    }
}

  

service层

接口:IItemsService

package com.test.service;

import com.test.pojo.Items;

import java.util.List;

public interface IItemsService {

    public List<Items> selectItems();
}

  

实现类:ItemsService

package com.test.service.impl;

import com.test.dao.IItemsDao;
import com.test.mapper.ItemsMapper;
import com.test.pojo.Items;
import com.test.service.IItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


public class ItemsService implements IItemsService {

    
    private IItemsDao itemsDao;


    public List<Items> selectItems()
    {
        return itemsDao.selectItems();
    }
}

  

4.创建spring的配置文件

applicationContext-ioc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.0.xsd">
   
 </beans>

  

5.在配置文件中添加注解扫描包

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.0.xsd">
   
   <!-- 设置注解 扫描 的包 -->
<context:component-scan base-package="com.test" />
   
 </beans>

  

  1. 在mvc各层中添加注解
package com.test.dao.impl;

import com.test.dao.IItemsDao;
import com.test.mapper.ItemsMapper;
import com.test.pojo.Items;

import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.List;

@Component
public class ItemsDao implements IItemsDao {

    public ItemsDao()
    {

    }
    public List<Items> selectItems()
    {
       return null;
    }
}
 

@Service
public class ItemsService implements IItemsService {

    @Autowired
    private IItemsDao itemsDao;   
    


    public List<Items> selectItems()
    {
        return itemsDao.selectItems();
    }
}

  

二.在spring中引入mybatis

1.导入mybatis jar包
<!-- 导入mybatis需要的jar包  -->
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.37</version>
</dependency>
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.4.6</version>
</dependency>
<dependency>
  <groupId>com.mchange</groupId>
  <artifactId>c3p0</artifactId>
  <version>0.9.5.2</version>
</dependency>

 <!-- 配置日志信息-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

  

2.导入spring整合mybatis架包
<!-- spring 整合 mybatis-->
  <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>
 <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.1.3.RELEASE</version>
  </dependency>

  

3.创建mapper文件
<?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.test.mapper.ItemsMapper">

    <select id="selectItems"  resultType="Items">
        select * from items;
    </select>

</mapper>

  

4.创建mapper文件的代理接口
package com.test.mapper;

import com.test.pojo.Items;

import java.util.List;

public interface ItemsMapper {

    public List<Items> selectItems();


}

  

5.创建mybatis配置文件

mybatis.xml文件

<?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>
<!-- 设置日志的输出方法 -->
    <settings>
           <setting name="logImpl" value="STDOUT_LOGGING" />
    </settings>

    <!-- 给pojo下面的类设置别名-->
    <typeAliases>
        <package name="com.test.pojo"/>
    </typeAliases>
    <mappers>

        <mapper resource="com/test/mapper/ItemsMapper.xml"/>
    </mappers>

</configuration>

  

6. 创建db.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123

  

7. 修改applicationContext-ioc.xml文件

将之前在mybatis文件中配置的数据源 交给spring来管理,并创建sqlSessionFactory对象

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 设置注解 扫描 的包 -->
    <context:component-scan base-package="com.test" />

    <!-- 导入db.properties文件 -->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

    <!-- 创建一个连接池对象 -->
    <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    </bean>

    <!-- 创建sqlSessionfactory对象-->
    <bean id="sqlSessionfactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="comboPooledDataSource"/>
        <property name="configLocation" value="classpath:mybatis.xml"/>
    </bean>

</beans>

  

8.修改dao层
package com.test.dao.impl;

import com.test.dao.IItemsDao;
import com.test.mapper.ItemsMapper;
import com.test.pojo.Items;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.List;

@Component
public class ItemsDao implements IItemsDao {
    
    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    public ItemsDao()
    {
      
    }

    public List<Items> selectItems()
    {
        SqlSession sqlSession= sqlSessionFactory.openSession();

        ItemsMapper itemsMapper= sqlSession.getMapper(ItemsMapper.class);

        List<Items> itemsList= itemsMapper.selectItems();

        return itemsList;
    }
}

  

9.在pom.xml文件中添加mapper.xml文件的路径

在build标签中添加

<resources>
 <resource>
   <!-- 将Mapper的映射文件拷贝出来 -->
   <directory>src/main/java</directory>
   <includes>
     <include>**/*.xml</include>
   </includes>
   <filtering>true</filtering>
 </resource>
 </resources>

  

 
10.测试
@Test
public void fun()
{
    ClassPathXmlApplicationContext classPathXmlApplicationContext=new ClassPathXmlApplicationContext("/applicationContext-ioc.xml");

    IItemsService itemsService= classPathXmlApplicationContext.getBean("itemsService",IItemsService.class);

     System.out.println(itemsService.selectItems());
}

  

三 给mapper接口创建代理,替代原dao层的功能

1.在applicationContext-ioc.xml文件中 添加

<!-- 配置映射文件的扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.test.mapper"/>
</bean>

  

  1. 修改service代码

将之前的

@Autowired
private IItemsDao itemsDao;

修改为

@Autowired
private ItemsMapper itemsMapper;

完整代码如下

 

package com.test.service.impl;

import com.test.dao.IItemsDao;
import com.test.mapper.ItemsMapper;
import com.test.pojo.Items;
import com.test.service.IItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class ItemsService implements IItemsService {


    @Autowired
    private ItemsMapper itemsMapper;

    public List<Items> selectItems()
    {
        return itemsMapper.selectItems();
    }

  


}
  1. 原来的dao层可以删除
  2. 测试代码不变
posted @ 2022-10-28 23:27  呆萌老师  阅读(32)  评论(0编辑  收藏  举报