spring整合mybatis

导读:本篇文章讲解 spring整合mybatis,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

1.mybatis实现数据库中学生信息的查询:

运行结果:

在这里插入图片描述

代码整体布局:

在这里插入图片描述

代码如下:

数据库/表:

create table tb_student
(
    student_id int primary key auto_increment,
    name varchar(20),
    sex char(1),
    birthday date
);

select * from tb_student;

insert into tb_student
(name,sex,birthday)
select '张三','男','2001-01-01' UNION
select '李四','女','2002-01-02' union
select '王五','男','2002-01-01' union
select '赵六','男','2003-01-03' union
select '孙琪','男','2002-01-01' union
select '高达','女','2005-01-01' union
select '郭靖','男','2002-11-01' union
select '黄蓉','女','2002-09-01' union
select '大武','男','2002-01-05';

在这里插入图片描述

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>mybatis_0822_KTLX2</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <spring.version>5.3.14</spring.version>
        <commons-dbcp.version>1.4</commons-dbcp.version>
        <mybatis.version>3.4.6</mybatis.version>
        <mybatis-spring.version>1.3.3</mybatis-spring.version>
        <mysql-connector-java.version>8.0.11</mysql-connector-java.version>
    </properties>
    <dependencies>
        <!--引入spring基础模块-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>repository.org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <!-- dbcp连接池 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>${commons-dbcp.version}</version>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!-- mysql驱动类 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>
        <!-- mybatis spring整合 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis-spring.version}</version>
        </dependency>
        <!--mybatis分页插件-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.4</version>
        </dependency>
        <!--mybatis通用mapper插件-->
        <dependency>
            <groupId>com.github.abel533</groupId>
            <artifactId>mapper</artifactId>
            <version>3.0.1</version>
        </dependency>
    </dependencies>


</project>

Student:

package com.entity;

import java.util.Date;

public class Student {
    private Integer studentId;
    private String name;
    private String sex;
    private Date birthday;

    public Student() {
    }

    public Student(Integer studentId, String name, String sex, Date birthday) {
        this.studentId = studentId;
        this.name = name;
        this.sex = sex;
        this.birthday = birthday;
    }

    public Integer getStudentId() {
        return studentId;
    }

    public void setStudentId(Integer studentId) {
        this.studentId = studentId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Student{" +
                "studentId=" + studentId +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                ", birthday=" + birthday +
                '}';
    }
}

StudentMapper:

package com.mapper;

import com.entity.Student;

import java.util.List;

public interface StudentMapper {
    List<Student> listAll();
}

StudentMapper.xml:

<?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.mapper.StudentMapper">

    <select id="listAll" resultType="student">
        select * from tb_student
    </select>

</mapper>

db.properties:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/70816_db?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf8&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=123456

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>
    <properties resource="db.properties"></properties>
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <typeAliases>
        <package name="com.entity"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <package name="com.mapper"/>
    </mappers>
</configuration>


Test:

package com.test;

import com.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class Test {
    public static void main(String[] args) throws IOException {
        InputStream inputStream= Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session=factory.openSession();
        StudentMapper studentMapper=session.getMapper(StudentMapper.class);
        System.out.println(studentMapper.listAll());

        session.commit();
        session.close();
    }
}

2.按照之前的结构,业务层搞起来。。。

参考:第三章 DAO模式《分层》 ② 代码https://blog.csdn.net/Liu_wen_wen/article/details/125967616
在这里插入图片描述

运行结果如下:

在这里插入图片描述

代码结构整体布局:

在这里插入图片描述

添加/修改的代码如下:

在这里插入图片描述

IStudentService:

package com.service;

import com.entity.Student;

import java.util.List;

public interface IStudentService {
    List<Student> listAll();
}

StudentServiceImpl:

package com.service.impl;

import com.entity.Student;
import com.mapper.StudentMapper;
import com.service.IStudentService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

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

public class StudentServiceImpl implements IStudentService {

    @Override
    public List<Student> listAll() {
        InputStream inputStream=null;
        try {
            inputStream= Resources.getResourceAsStream("mybatis-config.xml"); //ctrl+alt+t try+catch
            SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
            SqlSession session=factory.openSession();
            StudentMapper studentMapper=session.getMapper(StudentMapper.class);
            //System.out.println(studentMapper.listAll());
            List<Student> studentList=studentMapper.listAll();

            session.commit();
            session.close();

            return studentList;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Test2:

package com.test;

import com.entity.Student;
import com.service.IStudentService;
import com.service.impl.StudentServiceImpl;

import java.util.List;

public class Test2 {
    public static void main(String[] args) {
        IStudentService iStudentService=new StudentServiceImpl();
        List<Student> studentList=iStudentService.listAll();
        System.out.println(studentList);
    }
}

3.spring整合mybatis实现数据库中学生信息的查询:(待补充:增删改查)

运行结果:

在这里插入图片描述

思路图解:

在这里插入图片描述

代码结构整体布局:

在这里插入图片描述

添加/修改的代码如下:

spring-1.jsp:(新增)

<?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 https://www.springframework.org/schema/context/spring-context.xsd">
    <!--扫包-->
    <context:component-scan base-package="com.service"/>
    <!--配置数据库连接的属性配置文件 db.properties-->
    <context:property-placeholder location="db.properties"/>
    <!--配置数据库连接池-->
    <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--配置mybatis的SqlSessionFactory对象-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置mybatis factory的数据源-->
        <property name="dataSource" ref="ds"/>
        <!--配置类型别名-->
        <property name="typeAliasesPackage" value="com.entity"/>
        <!--配置mybatis主配置文件的路径,mybatis主配置文件中,可以定义特定的配置-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--配置mapper文件路径-->
        <property name="mapperLocations" value="classpath:com/mapper/*.xml"/>
    </bean>
    <!--配置Mapper接口-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--定义mapper接口所在的包-->
        <property name="basePackage" value="com.mapper"/>
        <!--配置sqlSessionFactory(底层会自动创建SqlSession从而)用于获取Mapper接口对象-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

</beans>

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>

    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

</configuration>


Test2:(修改)

package com.test;

import com.entity.Student;
import com.service.IStudentService;
import com.service.impl.StudentServiceImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

public class Test2 {
    public static void main(String[] args) {
//        IStudentService iStudentService=new StudentServiceImpl();
//        List<Student> studentList=iStudentService.listAll();
//        System.out.println(studentList);
        ApplicationContext ctx=new ClassPathXmlApplicationContext("spring-1.xml");
        IStudentService service=ctx.getBean(IStudentService.class);
        System.out.println(service.listAll());
    }
}

StudentServiceImpl:(修改)

package com.service.impl;

import com.entity.Student;
import com.mapper.StudentMapper;
import com.service.IStudentService;
import org.apache.ibatis.io.Resources;
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.Service;

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

@Service
public class StudentServiceImpl implements IStudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Override
    public List<Student> listAll() {
        return studentMapper.listAll();

//        InputStream inputStream=null;
//        try {
//            inputStream= Resources.getResourceAsStream("mybatis-config.xml"); //ctrl+alt+t try+catch
//            SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(inputStream);
//            SqlSession session=factory.openSession();
//            StudentMapper studentMapper=session.getMapper(StudentMapper.class);
//            //System.out.println(studentMapper.listAll());
//            List<Student> studentList=studentMapper.listAll();
//
//            session.commit();
//            session.close();
//
//            return studentList;
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return null;
    }
}

讲解参考:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

// A code block
var foo = 'bar';

// A code block
var foo = 'bar';

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118049.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!