Spring | SM整合(Spring+MyBatis)

0️⃣使用工具

  • 编辑器:IDEA企业版

  • 构建系统:Maven

  • 数据库:MySQL

1️⃣创建项目

🎏创建maven项目

选择新建项目,在E盘下创建名为SMDemo的项目,构建系统选择Maven.

🎏项目结构

  • src/main/java - java 逻辑代码类 存放的位置

  • src/main/resources - 配置文件、资源包等存放的位置

  • src/test/java - java测试类 存放的位置

  • pom.xml - 添加依赖的位置,maven自动帮我们导入依赖对应的jar包

2️⃣添加依赖

打开pom.xml文件,初始代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SMDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

</project>

🎏导入MyBatis与数据库相关依赖

添加<dependencies></dependencies>标签,在标签中加入相关依赖<dependency>

⭕MyBatis

       <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

⭕MySQL连接

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

⭕Druid数据库连接池

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.23</version>
        </dependency>

🎏导入Spring依赖

⭕Spring

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>

⭕Spring对ORM的支持

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>

🎏导入Spring与MyBatis关联的依赖

⭕Spring与MyBatis关联

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

🎏导入其他依赖

⭕junit

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>

🎏总览

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <!--mybatis与数据库相关-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.23</version>
        </dependency>

        <!--spring-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>

        <!--spring与mybatis关联-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.2</version>
        </dependency>

        <!--其他-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.2</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

点击右上角的小按钮刷新导入

3️⃣配置文件

🎏MyBatis阶段编写配置文件

在以前MyBatis阶段,我们编写项目会添加一个mybatis-config.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>
    <!--配置别名-->
    <typeAliases>
        <typeAlias type="com.app.pojo.User" alias="user"/>
    </typeAliases>

    <!--配置多个环境,default属性指定使用哪个环境-->
    <environments default="mysql">
        <!--配置具体环境-->
        <environment id="mysql">
            <!--
            配置事务管理器,type属性为JDBC,说明事务的管理底层使用JDBC事务
                Connection:
                    setAutoCommit(false):开启事务
                    commit():提交事务
                    rollback():回滚事务
            -->
            <transactionManager type="JDBC"/>
            <!--
            配置数据源,type属性有:
                POOLED:使用数据库连接池,底层由MyBatis实现
                UNPOOLED:没有使用数据库连接池
                JNDI:JavaEE技术之一,底层实现类似于操作系统的注册表
            -->
            <dataSource type="POOLED">
                <!--配置参数-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/db_study"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <!--配置关联映射文件-->
    <mappers>
        <!--配置具体映射文件,resource属性是关联映射文件的路径-->
        <mapper resource="com/app/dao/UserMapper.xml"/>
    </mappers>
</configuration>

🎏使用Spring编写配置文件

如今我们使用Spring,对于Dao的Dao.xml实现,我们需要使用Spring的IoC容器进行bean的管理。因此,我们不再需编写mybatis-config.xml,而是在Spring的配置文件中编写相关配置,将所有dao对应的dao.xml生成对应的实例。

⭕编写Spring配置文件

新建Spring的xml配置文件app.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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

</beans>

⭕扫描所有要被Spring管理实例(通过注解方式开发)

    <!--扫描所有要被Spring管理的实例-->
    <context:component-scan base-package="com.app"/>

⭕生成数据库连接池对象

    <!--配置数据库连接-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/db_study"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

⭕配置SqlSessionFactory

    <!--配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.app.pojo"/>
    </bean>

⭕生成dao.xml对应实例

    <!--扫描所有的dao,将所有dao对应的dao.xml生成对应的实例-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--依赖于sqlSessionFactory-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <property name="basePackage" value="com.app.dao"/>
    </bean>

🎏总览

<?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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd">

    <!--扫描所有要被Spring管理的实例-->
    <context:component-scan base-package="com.app"/>

    <!--配置数据库连接-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/db_study"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!--配置SqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--注入数据源-->
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.app.pojo"/>
    </bean>

    <!--扫描所有的dao,将所有dao对应的dao.xml生成对应的实例-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--依赖于sqlSessionFactory-->
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
        <property name="basePackage" value="com.app.dao"/>
    </bean>
</beans>

4️⃣打开数据库

🎏登录MySQL

管理员身份启动cmd,输入 net start mysql 启动 mysql 数据库服务。

net start mysql

输入用户名、密码登录 mysql 。

mysql -u 你的用户名 -p

查看 mysql 中的数据库,选择你的数据库

show databases;
use 你的数据库;

🎏创建 user 表

创建了一张 user 表,包含了 id,name,password 三个字段。其中 id 字段为主键,设置为自动增长

create table user(
    id int primary key auto_increment,
    name varchar(20),
    password varchar(20)
    );

🎏插入数据

插入若干条记录,用于后面的测试

insert into user values(null,"ketty","root");

查看表

select * from user;

5️⃣IDEA连接数据库

🎏选择MySQL

打开IDEA右侧的数据库连接,选择 + 号,选择MySQL.

🎏填写相关配置

填写相关配置,包括MySQL连接的用户名和密码,要连接的数据库,在URL的后面添加如下字段。

?serverTimezone=GMT&useSSL=false

连接成功后,可以看见我们数据库中的表。如果没有出现表,可以点击上面的刷新按钮刷新一下。

6️⃣生成Pojo、Dao类

🎏新建目录存放类

右键src/main/java目录,新建com.app.pojo、com.app.dao、com.app.service目录

🎏添加插件

找到插件,在搜索栏搜索better-mybatis-generator插件,点击添加。

🎏填写要生成类的相关信息

右键user类,选择mabatis-generate选项。

这里我们修改pojo类dao类dao.xml 三大类文件生成的位置(红框标注处),分别修改成我们刚刚新建的com.app.pojo包以及com.app.dao包。

❗注意如果你的mysql版本是8.0及以上,需要勾选下面mysql_8(红框标注处)。

❗查看mysql版本:打开cmd,输入mysql -V

mysql -V

修改完毕后,点击确定。第一次连接会要我们输入数据库连接的账号和密码。填写后在点击确定。

可以看见,我们的com.app.pojo和com.app.dao目录下多了四个文件。这四个文件是插件自动帮我们生成的,包括生成了一些常用的SQL单表操作,如根据条件查询,根据条件修改等。我们在service中就可以直接使用他们了。

7️⃣编写Service类

🎏编写接口

编写UserService接口,定义2个方法。

package com.app.service;

import com.app.pojo.User;

import java.util.List;

public interface UserService {
    List<User> getAllUser();

    long countByExample();
}

🎏编写实现类

创建Impl目录,编写UserServiceImpl实现类,实现2个方法。

package com.app.service.impl;

import com.app.dao.UserDao;
import com.app.pojo.User;
import com.app.pojo.UserExample;
import com.app.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired // 自动注入
    private UserDao userDao;

    @Override
    public List<User> getAllUser() {
        return userDao.selectByExample(null);
    }

    @Override
    public long countByExample() {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andNameLike("%t%");
        return userDao.countByExample(userExample);
    }
}

🎏Criteria

⭕在我们使用插件创建的类中,有一个之前没有见过的类UserExample。这个类是给我们拼接条件用的。

在SQL语句中,我们可能会使用到条件进行增删改查。UserExample中有一个内部类Criteria,通过这个内部类中的方法,我们可以拼接我们像要的条件。

⭕如上面的第二个方法中,我们使用了userDao的countByExample()方法。这个方法的SQL语句原本是如下这样:

select count(*) from user;

当我们使用criteria的andNameLike("%t%")方法时,这个方法帮助我们在查询语句后面添加了一个根据name模糊查询的条件。Criteria还有其他很多方法可供选择,这样我们就可以自由的根据需求去拼接我们想要的SQL语句。

⭕当然,如果我们在使用XXXByExample()方法时传入了null值,SQL就没有任何条件,如第一个方法那样,查询表中所有的记录。

8️⃣编写Test类

🎏创建Test类

src/test/java目录下创建com.app.test目录,创建UserTest类。

🎏编写Test类

注解执行顺序:@Before -> @Test -> @After

即@Before在@Test标注的方法前执行;

@After在@Test标注的方法后执行。

package com.app.test;

import com.app.dao.UserDao;
import com.app.pojo.User;
import com.app.service.UserService;
import com.app.service.impl.UserServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class UserTest {
    private ApplicationContext applicationContext;

    @Before
    public void before() {
        applicationContext = new ClassPathXmlApplicationContext("app.xml");
    }

    @Test
    public void test() {
        UserDao userDao = applicationContext.getBean(UserDao.class);
        User user = userDao.selectByPrimaryKey(8);
        System.out.println(user);
    }

    @Test
    public void testGetAllUser() {
        UserService userService = applicationContext.getBean(UserServiceImpl.class);
        List<User> users = userService.getAllUser();
        for (User user : users) {
            System.out.println(user);
        }
    }

    @Test
    public void testCountByExample() {
        UserService userService = applicationContext.getBean(UserServiceImpl.class);
        long i = userService.countByExample();
        System.out.println(i);
    }
}

🎏测试

⭕test()方法

⭕testGetAllUser()方法

⭕testCountByExample()方法

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值