首页 > 其他分享 >Spring整合Mybatis

Spring整合Mybatis

时间:2022-10-28 23:34:06浏览次数:58  
标签:Spring List test 整合 org Mybatis import com public

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. 测试代码不变

标签:Spring,List,test,整合,org,Mybatis,import,com,public
From: https://www.cnblogs.com/daimenglaoshi/p/16837826.html

相关文章

  • Mybatis 之 自定义别名处理插件
    请结合上一篇>>> MP插件原理  <<<  以及  >>>  Mybatis插件原理 <<< 进行查看查看 MP开发中,遇到的问题,动态的Wrapper产生的SQL中,主要出现在组合......
  • Mybatis 之 SQL 监控插件
    请结合上一篇>>> MP插件原理  <<<  以及 >>>  Mybatis插件原理 <<< 进行查看查看 使用场景:开发过程中监控每一条SQL语句的执行时长,已经顺便将SQL......
  • SpringBoot Starter缘起
    SpringBoot通过SpringBootStarter零配置自动加载第三方模块,只需要引入模块的jar包不需要任何配置就可以启用模块,遵循约定大于配置的思想。那么如何编写一个SpringBootSt......
  • Mybatis 之 Mybatis-Plus 插件
    请结合上一边 >>> Mybatis插件原理<<< 进行查看Mybatis中自己定义了一个自己的插件类接口 InnerInterceptor 其内部实现了一些现成的插件,如:PaginationInn......
  • SpringMVC
    SpringMVCSpringMVC简介SpringMVC概述SpringMVC是一种基于Java的实现MVC设计模型的请求驱动类型的轻量级Web框架,属于SpringFrameWork的后续产品,已经融合在Spr......
  • Spring JdbcTemplate
    SpringJdbcTemplateSpringJdbcTemplate基本使用JdbcTemplate概述它是spring框架中提供的一个对象,是对原始繁琐的JdbcAPI对象的简单封装。spring框架为我们提供了很多......
  • Spring整合Kafaka(二十六)
    1引入依赖<dependency><groupId>org.springframework.kafka</groupId><artifactId>spring-kafka</artifactId></dependency>2配置Kafka配置server、cons......
  • MyBatis
    MyBatisMybatis简介原始jdbc操作的分析原始jdbc开发存在的问题如下:数据库连接创建、释放频繁造成系统资源浪费从而影响系统性能sql语句在代码中硬编码,造成代码不易......
  • SSM整合
    SSM整合原始方式整合啥都不做,浑然天成,相当于复习前面的内容。创建数据库及对应表类创建Maven工程导入Maven坐标<?xmlversion="1.0"encoding="UTF-8"?><project......
  • Spring Boot
    SpringBootSpringBoot基础SpringBoot简介SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化Spring应用的初始搭建以及开发过程,简单讲就是牺牲项目的自由......