springboot+springMVC+mybatis整合mysql方法,实现 增删该查 图文教程

自己学习了springboot   springMVC   mybatis   ,但是网上找了很多整合的视频和博客,发现自己太菜了看不懂,所以决定自己摸索。结果成功了。写这个博客来总结经验。下面是步骤:

数据库方面:

使用mysql创建一个数据库,数据库名称为ssm,数据库的编码为utf-8,整理用utf8-general-ci,创建一个数据表,数据表名为ssm_news。

以下为数据表的所有字段:

我们主要做的就是通过创建springboot项目结合mybatis查出数据表中的数据。

配置开发环境并创建项目:

1.在本机上配置jdk1.8

2.打开eclipse,点击help,点击eclipse marketplace...,选择popular选项,找到spring tools 3 选项,点击install按钮,等待安装完成。如下:

 3.下载完成后,创建项目。file ——> new ——> other... ——> spring boot ——> spring starter project.

如下:并在红色部分填写项目名称

把项目需要的插件jar包依赖勾选,找不到的可以在下图蓝色部分找,选完后直接下一步,finish等待项目创建完成即可。

 整合过程:

项目创建完成后的文件目录如下图:

展开src/main/java目录,我们在该目录下创建一下文件夹:(注意,目录的包含层级关系不要乱)

controller:控制器,处理逻辑的Java代码文件存放位置

interfaces:接口文件存放位置。数据库的查询方式不仅可以通过配置映射文件,还能通过注解的方式写在接口中。(暂时用不到)

mappers:映射文件存放位置,用于存放映射数据表的xml文件

model:数据模型。存放数据模型java文件的位置

mybatisUtil:工具类存放位置,存放mybatis读取配置等工具类

test:用于测试类的存放,存放Junit的测试类

SsmDemo2Application.java:自动生成的文件(不用管)

db.properties:配置数据库连接的参数文件

mybatis-config.xml:mybatis的配置文件

创建以上的文件存放目录后。开始创建mybatis-config.xml配置文件

在上述对应的位置中创建mybatis-config.xml文件。注意文件的位置

在文件中放入一下的配置信息:(这些配置信息都是可以在mybatis官网中查找到的,也可以从官网上拷贝粘贴下来用):

<?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="com/example/demo/db.properties"></properties><!-- 将数据库的连接参数存放在外部文件db.properties中 resource中填写的是数据库配置文件的地址和文件名 -->
  
  <environments default="development">
    <environment id="Ssm"><!-- 数据库的连接配置参数 使用当前数据库连接时要使用当前的ID名。所以,当使用多个数据库是时候,可以配置多个 <environment id=""></environment>标签中的数据库连接参数-->
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED"><!--标记从连接池中使用-->
        <property name="driver" value="${db.driver}"/><!-- db.driver对应外部文件db.properties中的参数-->
        <property name="url" value="${db.url}"/><!-- db.url对应外部文件db.properties中的参数-->
        <property name="username" value="${db.username}"/><!-- db.username对应外部文件db.properties中的参数-->
        <property name="password" value="${db.password}"/><!-- db.password对应外部文件db.properties中的参数-->
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <!-- <mapper class="www.zhangxiaosan.mybatis.Tb_users.Tb_usersMapper"/> --><!-- 通过接口进行配置 ,注意,此处注册的是接口的名称,而不是接口文件名-->
    <mapper resource="com/example/demo/mappers/Ssm_newsMapper.xml"/><!--这里放的是映射的数据表的xml配置文件的路径,当有多个数据表时,可在此配置多个xml-->
  </mappers>
</configuration>

创建db.properties文件,配置数据库连接的参数文件。

注意:db.driver   db.url   db.username  db.password 都是在上面的配置文件中property 标签中的占位符名字,两者要对应不能错。各个参数的值填写自己对应的数据库连接信息即可。(此处采用的是mysql)

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC&useSSL=false
db.username=root
db.password=root

在mybatisUtil文件夹中创建mybatis工具类MybatisUtil,用于读取配置

package com.example.demo.mybatisUtil;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

/**
 * 读取mybatis-config.xml配置文件的配置
 * */
public class MybatisUtil {
	public static SqlSession openSession() throws IOException{
		String resource="com/example/demo/mybatis-config.xml";//此处要填写mybatis-config.xml的路径
		InputStream in = Resources.getResourceAsStream(resource);
		SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(in,"Ssm");//Ssm为mybatis-config.xml配置中的<environment id="Ssm"></environment>标签中的ID名
		return sessionFactory.openSession();
	} 
}

创建数据表对应的模型文件,在model文件夹中创建名为Ssm_newsModel.java的数据表模型文件。命名格式:数据表名+Model

将数据表中对应的字段都封装(获取get、set、toString方法)

package com.example.demo.model;

/**
 * ssm_news表的实体类
 */
public class Ssm_newsModel {
	private int id;
	private String news_title;
	private String news_author;
	private int news_time;
	private String news_content;
	private int news_state;
	private int create_time;
	private int update_time;
	private int delete_time;
	private String create_ip;

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getNews_title() {
		return news_title;
	}

	public void setNews_title(String news_title) {
		this.news_title = news_title;
	}

	public String getNews_author() {
		return news_author;
	}

	public void setNews_author(String news_author) {
		this.news_author = news_author;
	}

	public int getNews_time() {
		return news_time;
	}

	public void setNews_time(int news_time) {
		this.news_time = news_time;
	}

	public String getNews_content() {
		return news_content;
	}

	public void setNews_content(String news_content) {
		this.news_content = news_content;
	}

	public int getNews_state() {
		return news_state;
	}

	public void setNews_state(int news_state) {
		this.news_state = news_state;
	}

	public int getCreate_time() {
		return create_time;
	}

	public void setCreate_time(int create_time) {
		this.create_time = create_time;
	}

	public int getUpdate_time() {
		return update_time;
	}

	public void setUpdate_time(int update_time) {
		this.update_time = update_time;
	}

	public int getDelete_time() {
		return delete_time;
	}

	public void setDelete_time(int delete_time) {
		this.delete_time = delete_time;
	}

	public String getCreate_ip() {
		return create_ip;
	}

	public void setCreate_ip(String create_ip) {
		this.create_ip = create_ip;
	}

	@Override
	public String toString() {
		return "Ssm_newsModel [id=" + id + ", news_title=" + news_title + ", news_author=" + news_author
				+ ", news_time=" + news_time + ", news_content=" + news_content + ", news_state=" + news_state
				+ ", create_time=" + create_time + ", update_time=" + update_time + ", delete_time=" + delete_time
				+ ", create_ip=" + create_ip + "]";
	}

}

创建表对应的映射xml文件。在mappers文件夹中创建文件Ssm_newsMapper.xml。格式:数据表名+Mapper.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.example.demo.Ssm_newsMapper"><!-- 若采用接口方式,此处的值为接口名的路径地址,而非接口文件的路径地址 -->
<!--select 标签标示使用的是查询语句 使用该查询语句时使用此ID名 resultType为返回值类型。填写上Ssm_newsModel.java的路径标示返回的是一个模型  #{id}标示的是占位符,存在防止sql注入的功能(${id}此写法存在风险,会被注入,尽量不使用)-->
  <select id="selectSsm_newById" 
      resultType="com.example.demo.model.Ssm_newsModel">
    select * from Ssm_news where id = #{id}
  </select>
  
  <select id="selectSsm_newsAll" 
      resultType="com.example.demo.model.Ssm_newsModel">
    select * from Tb_users
  </select>
  
  <!--模糊查找 parameterType表示的是参数类型,即传入sql语句的参数的类型,若不写该属性,默认参数类型为int-->
  <select id="selectSsm_newByUsername_Like" 
      parameterType="com.example.demo.model.Ssm_newsModel" 
      resultType="com.example.demo.model.Ssm_newsModel">      
      select * from Tb_users where username LIKE "%"#{username}"%"
    	<!-- <where>
            <if test="username != null and username != ''">
                username LIKE "%"#{username}"%"
            </if>
        </where> -->

    
  </select>
  
    <!--插入-->
  <insert id="insertSsm_new" 
      parameterType="com.example.demo.model.Ssm_newsModel">
      insert into Tb_users (username,password) values(#{username},#{password})
  </insert>
  
 <!--更新-->
  <update id="updateSsm_new" 
      parameterType="com.example.demo.model.Ssm_newsModel">
      update Tb_users set username=#{username}, password=#{password} where id=#{id}
  </update>
  
 <!--删除-->
  <delete id="deleteSsm_new" 
      parameterType="int">
      delete from Tb_users where id=#{id}
  </delete>
</mapper>

测试数据:

在test文件夹下创建Junit Test 测试类Ssm_newsTest.java

package com.example.demo.test;

import static org.junit.Assert.*;

import java.io.IOException;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import com.example.demo.model.Ssm_newsModel;
import com.example.demo.mybatisUtil.MybatisUtil;

public class Ssm_newsTest {

	@Test
	public void test() {
		fail("Not yet implemented");
	}
	

    //测试数据
	@Test
	public void selectSsm_newById_test() throws IOException {
		SqlSession session = MybatisUtil.openSession();
        
        /*statement存放的是Ssm_newMapper.xml配置文件的对应功能:格式为:Ssm_newMapper.xml为文件中的<mapper namespace="com.example.demo.Ssm_newsMapper">标签中的namespace的值+select标签中的ID名*/
		String statement = "com.example.demo.Ssm_newsMapper.selectSsm_newById";
		Ssm_newsModel ssm_newsModel = session.selectOne(statement, 1);//selectone表示查询一条记录,1代表的是记录的ID
		System.out.println(ssm_newsModel);
		session.close();
	}
}

运行Junit的selectSsm_newById_test方法后的结果为:

数据已经查询出来了~

删改查之后再加上吧~

 

 

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 6
    评论
SpringBoot是一个用于简化Spring应用程序开发的框架。它并没有官方实现Mybatis的启动器,但是Mybatis官方自己实现了一个启动器,可以在pom.xml文件中引入依赖来使用。\[1\]为了开发web工程,需要在pom.xml中引入spring-boot-starter-web依赖,这个依赖包含了Spring WebMVC和Tomcat等web开发的特性。\[2\]在使用SpringBoot快速入门时,需要进行以下步骤:添加依赖spring-boot-starter-webspring-boot-starter-parent,创建控制器Controller和DispatcherServlet前端控制器,然后启动SpringBoot项目。\[3\]在控制器类上使用注解来标识该类是一个业务控制器,比如使用@SpringBootApplication注解来标识启动类,@Controller注解来标识控制器类。\[3\]至于整合SpringBootSpringMVCMybatis框架,可以通过配置文件和注解来实现。具体的整合方式可以根据项目需求和实际情况进行选择和配置。 #### 引用[.reference_title] - *1* *3* [springboot整合mybatis框架](https://blog.csdn.net/qq_42652006/article/details/126833620)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [springboot整合mybatisspringmvc](https://blog.csdn.net/sunhongbing1024/article/details/83186783)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小张帅三代

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值