spring整合mybatis(实现数据的增删改查)

这篇具有很好参考价值的文章主要介绍了spring整合mybatis(实现数据的增删改查)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

一、专业术语解释

1、spring:是分层的Java SE/EE应用full - stack轻量级开源框架以IoC(控制反转)和AOP(面向切面编程)为内核,提供展现层spring MVC 和 spring JDBC等众多企业级应用技术。

2、mybatis:是一个持久层框架。原始连接数据库是通过JDBC的API来操作的,过程繁琐,而mybatis是对JDBC的封装

二、spring整合mybatis完整步骤

1、准备工作(新建项目及新建包)

        1.1、

spring整合mybatis(实现数据的增删改查)

        1.2、

spring整合mybatis(实现数据的增删改查)

        1.3、

spring整合mybatis(实现数据的增删改查)

        1.4、

spring整合mybatis(实现数据的增删改查)

        1.5、 

spring整合mybatis(实现数据的增删改查)

        1.6、删除src包下,暂时不需要的包,同时在src/main包下新建java包、resource包以及在src包下新建test包和resource包。新建后的原始maven文件

spring整合mybatis(实现数据的增删改查)

        1.7、删除掉main下的webapp包,接下来就是在main下新建几个包

步骤:file——project structure

spring整合mybatis(实现数据的增删改查)

        1.8、 spring整合mybatis(实现数据的增删改查)

        1.9、 再在java包下新建dao包、servcie包、entity包、config包,在resource包下新建一个文件jdbc.properties

        dao包:数据层,在这里主要写操作数据库的接口

        service包:逻辑控制层,主要处理一些逻辑,目前还用不上逻辑处理,主要是中转数据层

        entity层:实体层,这一层主要存放数据信息,这里的数据和数据库信息保持一致

        config包:这一层主要数存放spring的配置类、jdbc配置类和mybatis类

        jdbc.properties:这个文件主要存放连接数据库的一些信息

spring整合mybatis(实现数据的增删改查)

        1.10、准备工作的最后一步就是导入需要的架包了,spring整合mybatis所需架包如下

        在pom.xml导入架包哈!导完架包后记得刷新一下maven

<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

<!--    spring架包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>
<!--    数据源-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
        <version>1.1.16</version>
    </dependency>

<!--    mybatis包-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.5</version>
    </dependency>



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

<!--    mysql-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.49</version>
    </dependency>

<!--    spring-jdbc-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.2.10.RELEASE</version>
    </dependency>

<!--    记录日志-->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>
  </dependencies>

 2、准备工作已经完成,现在就是整个项目的开始了

        2.1、SpringConfig.java

package config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;

//这个程序到时候由主程序创建一个对象引入
//开启纯注解模式
@Configuration
//既然已经开启了注解模式,那么主程序主要扫描那些包了
//扫描包
@ComponentScan({"dao","service"})
//jdbc.properties配置识别数据的一些信息,如何识别了
@PropertySource(value = "classpath:jdbc.properties",encoding = "utf-8")
//既然是spring整合mybatis,肯定有一个mybatis.java,所以新建mybatis类
//既然是连接数据库,连接数据库的信息写哪里了,所以再新建一个jdbcCOnfig类
//如何引入这个两个文件了
@Import({MybatisConfig.class,JdbcConfig.class})
public class SpringConfig {
}

         2.2、jdbc.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/user?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
jdbc.username=root
jdbc.password=123456

spring整合mybatis(实现数据的增删改查)

         2.3、jdbcConfig.java

package config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;

public class JdbcConfig {

//    连接数据:数据库地址、数据源、数据库名、数据库密码

    @Value("${jdbc.driver}")
    private String driver;

    @Value("${jdbc.url}")
    private String url;

    @Value("${jdbc.username}")
    private String username;

    @Value("${jdbc.password}")
    private String password;


//    数据源
    public DruidDataSource druidDataSource() {
        DruidDataSource ds = new DruidDataSource();

        ds.setDriverClassName(driver);
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);

        return ds;
    }

}

        2.4、mybatis.java

package config;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;

import javax.sql.DataSource;

public class MybatisConfig {

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {

        SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean();
//        扫描实体类
        ssfb.setTypeAliasesPackage("entity");
//        加载数据源
        ssfb.setDataSource(dataSource);

        return ssfb;
    }

//    接下来就是扫描dao层
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer maper = new MapperScannerConfigurer();

        maper.setBasePackage("dao");

        return maper;
    }
}

        2.5、entity层 student类

package entity;

public class Student {

    private int id;
    private String name;
    private String sex;

    public Student(int id, String name, String sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    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 String getSex() {
        return sex;
    }

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

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

spring整合mybatis(实现数据的增删改查)

向数据库添加两条数据

spring整合mybatis(实现数据的增删改查)

 文章来源地址https://www.toymoban.com/news/detail-477905.html

        2.6、dao层,主要通过接口中mysql语句来对数据库操作

package dao;

import entity.Student;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface StudentDao {


//    查询
    @Select("SELECT * FROM student")
    List<Student> queryAll();
}

spring整合mybatis(实现数据的增删改查)

        2.7、 service层,分别新建接口和实现类

实现类:

package service.Impl;

import dao.StudentDao;
import entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.StudentService;

import java.util.List;

@Service("StudentService")
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    public List<Student> queryAll() {

        return studentDao.queryAll();
    }
}
接口类
package service;

import entity.Student;

import java.util.List;

public interface StudentService {

    List<Student> queryAll();
}

2.8、以上是一个spring整合mybatis的简单查询功能,先来测试一下,然后再做增删查改

import config.SpringConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import service.StudentService;

public class StudentTest {

    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);

        StudentService studentServices = ctx.getBean(StudentService.class);
        System.out.println(studentServices.queryAll());
    }
}

spring整合mybatis(实现数据的增删改查)

3、增加数据:即向数据库中插入一条数据,写代码的顺序是,现在dao层写一个方法和mysql语句——再去service层的实现类调用dao和对实现类的方法做一个接口——再去测试类中新建main函数,调用service层接口,这就是整个项目的流程

        3.1、在dao层写接口方法和mysql语句

package dao;

import entity.Student;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface StudentDao {


//    查询
    @Select("SELECT * FROM student")
    List<Student> queryAll();

//    增加数据
    @Insert("INSERT INTO student(id,name,sex) VALUE(#{id},#{name},#{sex})")
    void insert(Student student);

//    按id值查询
    @Select("SELECT * FROM student WHERE id = #{id}")
    List<Student> findId(Integer id);

//    删除数据,根据id来删除数据
    @Delete("DELETE FROM student WHERE id = #{id}")
    void delete(Integer id);

//    更新数据
    @Update("INSERT INTO student(id,name,sex) VALUE(#{id},#{name},#{sex})")
    void update(Student student);
}

        3.2、service层

      实现类:

package service.Impl;

import dao.StudentDao;
import entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import service.StudentService;

import java.util.List;

@Service("StudentService")
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentDao studentDao;

    public List<Student> queryAll() {
        return studentDao.queryAll();
    }

    public void insert(Student student) {
        studentDao.insert(student);
    }

    public List<Student> findId(Integer id) {
        return studentDao.findId(id);
    }

    public void delete(Integer id) {
        studentDao.delete(id);
    }

    public void update(Student student) {
        studentDao.insert(student);
    }

}

接口

package service;

import entity.Student;

import java.util.List;

public interface StudentService {

    List<Student> queryAll();

    void insert(Student student);

    List<Student> findId(Integer id);

    void delete(Integer id);

    void update(Student student);
}

3.3、测试

import config.SpringConfig;
import entity.Student;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import service.StudentService;

public class StudentTest {

    public static void main(String[] args) {
        ApplicationContext ctx = new AnnotationConfigApplicationContext(SpringConfig.class);

        StudentService studentServices = ctx.getBean(StudentService.class);
        System.out.println(studentServices.queryAll());

        Student stu1 = new Student(202366,"chatGPT","Ai");
        studentServices.insert(stu1);

        System.out.println(studentServices.findId(202366));

        studentServices.delete(202302);

        Student stu2 = new Student(202399,"王五","男");
        studentServices.update(stu2);
        System.out.println(studentServices.queryAll());


    }
}

3.4、增删改查

spring整合mybatis(实现数据的增删改查)

spring整合mybatis(实现数据的增删改查)

spring整合mybatis(实现数据的增删改查)

spring整合mybatis(实现数据的增删改查) 

 spring整合mybatis(实现数据的增删改查)

 以上就是spring整合mybatis的全过程!!!

 

 

到了这里,关于spring整合mybatis(实现数据的增删改查)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java编程精选:掌握Spring Boot、MySQL和MyBatis的增删改查实战

    当使用Spring Boot和MyBatis来实现对数据库的操作时,可以按照以下步骤进行配置和开发: 确保已经在项目的 pom.xml 文件中添加了Spring Boot和MyBatis的依赖。 配置数据库连接信息。在 application.properties 文件中添加以下配置: 请根据实际情况修改数据库连接URL、用户名和密码。 创建

    2024年02月08日
    浏览(76)
  • MyBatis-Plus 基础操作指南:实现高效的增删改查

        大家好,今天我们来聊聊如何使用 MyBatis-Plus(接下来简称为 MP),一个流行的 MyBatis 增强工具,来简化和加速我们的数据库操作。如果你是一位初学者,不用担心,我将带你从头到尾详细了解 MP 的使用方法,特别是如何实现基本的增删改查操作。     在开始详细介绍之

    2024年02月05日
    浏览(24)
  • 一个简单的增删改查Spring boot项目教程(完整过程,附代码)(从搭建数据库到实现增删改查功能),Springboot学习,Springboot项目,

    这里将会介绍怎么去搭建一个简单增删改查的Springboot项目,认真看完我相信你一定能够学会,并且附有完整代码; 首先要进行增删改查肯定是要有供操作的数据库; 这里我是用的SQLyog来搭建的,随便用什么都可以,只要能确保给项目一个配套的数据库就行; 打开IDEA,创建

    2024年02月15日
    浏览(47)
  • MyBatis的增删改查

            本章学习MyBatis的基本crud操作。 java程序如下: ①使用map集合传参 ②使用pojo传参 SQL语句如下:  运行结果: ps:如果采用map集合传参,#{} 里写的是map集合的key,如果key不存在不会报错,数据库表中会插入NULL。 ps:如果采用POJO传参,#{} 里写的是POJO类中get方法的方法

    2024年02月08日
    浏览(24)
  • MyBatis 单表的增删改查

    ✅作者简介:2022年 博客新星 第八 。热爱国学的Java后端开发者,修心和技术同步精进。 🍎个人主页:Java Fans的博客 🍊个人信条:不迁怒,不贰过。小知识,大智慧。 💞当前专栏:SSM 框架从入门到精通 ✨特色专栏:国学周更-心性养成之路 🥭本文内容:MyBatis 单表的增删

    2024年02月21日
    浏览(30)
  • Mybatis案例-商品的增删改查

    JDBC完成: https://blog.csdn.net/meini32/article/details/131981238 1. aim 要完成的功能列表清单: 1. 查询 查询所有数据 查看详情 条件查询 2. 添加 3. 修改 修改全部字段 修改动态字段 4. 删除 删除一个 批量删除 2.环境准备 数据库表tb_brand 实体类Brand 测试用例 安装MyBatis×插件 数据库表: 实

    2024年02月14日
    浏览(27)
  • Springboot整合mybatis实现增删改查(crud)

    今天我们来学习一个Springboot案例!! 那么什么是SpringBoot技术呢? Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。 该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置。 Spring Boot致力于在蓬

    2024年01月22日
    浏览(32)
  • springboot-mybatis的增删改查

    目录 一、准备工作 二、常用配置  三、尝试  四、增删改查 1、增加 2、删除 3、修改 4、查询 五、XML的映射方法 实施前的准备工作: 准备数据库表 创建一个新的springboot工程,选择引入对应的起步依赖(mybatis、mysql驱动、lombok) application.properties中引入数据库连接信息 创建

    2024年02月14日
    浏览(27)
  • layui实现(学生)数据的增删改查

    查询 添加: 点击添加按钮: 添加成功! 修改: 点击编辑按钮: 修改信息数据,点击提交: 修改数据成功! 删除: 点击删除按钮: 点击确定,删除成功! 分页: 由于数据有限,选择5条/页,进行分页: 批量删除: 首先勾选想要删除的行,点击批量删除: 删除成功: 补

    2023年04月09日
    浏览(27)
  • 化繁为简,MyBatis-Plus 里面的增删改查

    在当前盛行的 SpringBoot 项目中,整合持久层这一块,目前主流的有两种:JPA 和 MyBatis-Plus。至于哪个用的更多一些,这个主要还是看每个公司的技术架构,但硬是要说一个最为常用的,我认为是 MyBatis-Plus,而在这里也是对 MyBatis-Plus 的一个使用进行演示 好了,废话不多说,直

    2024年02月04日
    浏览(28)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包