SpringMVC+Mybatis基础知识和配置
SpringMVC和Mybatis简单的记录一下,因为现在有比较新的SpringBoot和Mybatis plus简化了很多步骤。
SpringMVC
使用
- 创建maven项目,pom.xml
<dependencies><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.0.11.RELEASE</version></dependency>
</dependencies>
- 在 web.xml 中配置 DispatcherServlet
<!DOCTYPE web-app PUBLIC"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN""http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app><display-name>Archetype Created Web Application</display-name><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc.xml</param-value></init-param></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>/</url-pattern></servlet-mapping>
</web-app>
- springmvc.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"xmlns:mvc="http://www.springframework.org/schema/mvc"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.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"><!-- 自动扫描 --><context:component-scan base-package="com.southwind"></context:component-scan><!-- 配置视图解析器 --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/"></property><property name="suffix" value=".jsp"></property></bean></beans>
- 创建 Handler
package com.southwind.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;@Controller
public class HelloHandler {@RequestMapping("/index")public String index(){System.out.println("执行了index...");return "index";}
}
Spring MVC REST
REST:Representational State Transfer,资源表现层状态转换,是目前比较主流的一种互联网软件架构,它结构清晰、标准规范、易于理解、便于扩展。
- 资源(Resource)
网络上的一个实体,或者说网络中存在的一个具体信息,一段文本、一张图片、一首歌曲、一段视频等等,总之就是一个具体的存在。可以用一个 URI(统一资源定位符)指向它,每个资源都有对应的一个特定的 URI,要获取该资源时,只需要访问对应的 URI 即可。
- 表现层(Representation)
资源具体呈现出来的形式,比如文本可以用 txt 格式表示,也可以用 HTML、XML、JSON等格式来表示。
- 状态转换(State Transfer)
客户端如果希望操作服务器中的某个资源,就需要通过某种方式让服务端发生状态转换,而这种转换是建立在表现层之上的,所有叫做"表现层状态转换"。
特点
- URL 更加简洁。
- 有利于不同系统之间的资源共享,只需要遵守一定的规范,不需要进行其他配置即可实现资源共享。
如何使用
REST 具体操作就是 HTTP 协议中四个表示操作方式的动词分别对应 CRUD 基本操作。
GET 用来表示获取资源。
POST 用来表示新建资源。
PUT 用来表示修改资源。
DELETE 用来表示删除资源。
Handler`
import entity.Student;
import entity.User;
import repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.*;import javax.servlet.http.HttpServletResponse;
import java.util.Collection;@RestController
@RequestMapping("/rest")
public class RESTHandeler {@Autowiredprivate StudentRepository studentRepository;@GetMapping("/findAll")public Collection<Student> findAll(HttpServletResponse response){response.setContentType("text/json;charset=UTF-8");return studentRepository.findAll();}@GetMapping("/findById/{id}")public Student findById(@PathVariable("id") long id){return studentRepository.findById(id);}@PostMapping("/save")public void save(@RequestBody Student student){studentRepository.saveOrUpdate(student);}@PutMapping("/update")public void update(@RequestBody Student student){studentRepository.saveOrUpdate(student);}@DeleteMapping("/deleteById/{id}")public void deleteById(@PathVariable("id") long id){studentRepository.deleteById(id);}}
StudentRepository
package repository;import entity.Student;import java.util.Collection;public interface StudentRepository {public Collection<Student> findAll();public Student findById(long id);public void saveOrUpdate(Student student);public void deleteById(long id);
}
StudentRepositoryImpl
import entity.Student;
import repository.StudentRepository;
import org.springframework.stereotype.Repository;import java.util.Collection;
import java.util.HashMap;
import java.util.Map;@Repository
public class StudentRepositoryImpl implements StudentRepository {private static Map<Long,Student> studentMap;static{studentMap = new HashMap<>();studentMap.put(1L,new Student(1L,"张三",22));studentMap.put(2L,new Student(2L,"李四",23));studentMap.put(3L,new Student(3L,"王五",24));}@Overridepublic Collection<Student> findAll() {return studentMap.values();}@Overridepublic Student findById(long id) {return studentMap.get(id);}@Overridepublic void saveOrUpdate(Student student) {studentMap.put(student.getId(),student);}@Overridepublic void deleteById(long id) {studentMap.remove(id);}
}
Mybatis
MyBatis
ORMapping: Object Relationship Mapping 对象关系映射
对象指⾯向对象
关系指关系型数据库
Java 到 MySQL 的映射,开发者可以以⾯向对象的思想来管理数据库。
如何使⽤
新建 Maven ⼯程,pom.xml
<dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.6</version><scope>provided</scope></dependency>
</dependencies> <build><resources><resource><directory>src/main/java</directory><includes><include>**/*.xml</include></includes></resource></resources>
</build>
新建数据表
use mybatis;
create table t_account(id int primary key auto_increment,username varchar(11),password varchar(11),age int
)
新建数据表对应的实体类 Account
package entity;
import lombok.Data;
@Data
public class Account {private long id;private String username;private String password;private int age; }
创建 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><!-- 配置MyBatis运⾏环境 --><environments default="development"><environment id="development"><!-- 配置JDBC事务管理 --><transactionManager type="JDBC"></transactionManager><!-- POOLED配置JDBC数据源连接池 --><dataSource type="POOLED"><property name="driver" value="com.mysql.cj.jdbc.Driver">
</property><property name="url"
value="jdbc:mysql://localhost:3306/mybatis?
useUnicode=true&characterEncoding=UTF-8"></property><property name="username" value="root"></property><property name="password" value="root"></property></dataSource></environment></environments>
</configuration>
通过 Mapper 代理实现⾃定义接⼝
⾃定义接⼝,定义相关业务⽅法。
编写与⽅法相对应的 Mapper.xml。
1、⾃定义接⼝
package repository;
import entity.Account;
import java.util.List;
public interface AccountRepository {public int save(Account account);public int update(Account account);public int deleteById(long id);public List<Account> findAll();public Account findById(long id);
}
2、创建接⼝对应的 Mapper.xml,定义接⼝⽅法对应的 SQL 语句。
statement 标签可根据 SQL 执⾏的业务选择 insert、delete、update、select。
MyBatis 框架会根据规则⾃动创建接⼝实现类的代理对象。
规则:
Mapper.xml 中 namespace 为接⼝的全类名。
Mapper.xml 中 statement 的 id 为接⼝中对应的⽅法名。
Mapper.xml 中 statement 的 parameterType 和接⼝中对应⽅法的参数类型⼀致。
Mapper.xml 中 statement 的 resultType 和接⼝中对应⽅法的返回值类型⼀致。
<?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="mybatis.repository.AccountRepository"><insert id="save" parameterType="mybatis.entity.Account">insert into t_account(username,password,age) values (#{username},#{password},#{age});</insert><update id="update" parameterType="mybatis.entity.Account">update t_account set username=#{username},password=#{password},age=#{age} where id=#{id};</update><delete id="deleteById" parameterType="long">delete from t_account where id=#{id};</delete><select id="findAll" resultType="mybatis.entity.Account">select * from t_account;</select><select id="findById" parameterType="long" resultType="mybatis.entity.Account">select * from t_account where id=#{id};</select>
</mapper>
3、在 config.xml 中注册 AccountRepository.xml
<!-- 注册AccountMapper.xml --><mappers><mapper resource="mybatis/mapper/AccountMapper.xml"></mapper><mapper resource="mybatis/repository/AccountRepository.xml"></mapper></mappers>
4、调⽤接⼝的代理对象完成相关的业务操作
package mybatis.test;import mybatis.entity.Account;
import mybatis.repository.AccountRepository;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.InputStream;
import java.util.List;public class Test2 {public static void main(String[] args) {InputStream inputStream =
Test.class.getClassLoader().getResourceAsStream("config.xml");SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new
SqlSessionFactoryBuilder();SqlSessionFactory sqlSessionFactory =
sqlSessionFactoryBuilder.build(inputStream);SqlSession sqlSession = sqlSessionFactory.openSession();//获取实现接⼝的代理对象AccountRepository accountRepository =
sqlSession.getMapper(AccountRepository.class);//添加对象
// Account account = new Account(3L,"王五","111111",24);
// int result = accountRepository.save(account);
// sqlSession.commit();//查询全部对象
// List<Account> list = accountRepository.findAll();
// for (Account account:list){// System.out.println(account);
// }
// sqlSession.close();//通过id查询对象
// Account account = accountRepository.findById(3L);
// System.out.println(account);
// sqlSession.close();//修改对象
// Account account = accountRepository.findById(3L);
// account.setUsername("⼩明");
// account.setPassword("000");
// account.setAge(18);
// int result = accountRepository.update(account);
// sqlSession.commit();
// System.out.println(result);
// sqlSession.close();//通过id删除对象int result = accountRepository.deleteById(3L);System.out.println(result);sqlSession.commit();sqlSession.close();}
}
逆向⼯程
MyBatis 框架需要:实体类、⾃定义 Mapper 接⼝、Mapper.xml
传统的开发中上述的三个组件需要开发者⼿动创建,逆向⼯程可以帮助开发者来⾃动创建三个组件,减
轻开发者的⼯作量,提⾼⼯作效率。
如何使⽤
MyBatis Generator,简称 MBG,是⼀个专⻔为 MyBatis 框架开发者定制的代码⽣成器,可⾃动⽣成
MyBatis 框架所需的实体类、Mapper 接⼝、Mapper.xml,⽀持基本的 CRUD 操作,但是⼀些相对复
杂的 SQL 需要开发者⾃⼰来完成。
新建 Maven ⼯程,pom.xml
<dependencies><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.4.5</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.11</version></dependency><dependency><groupId>org.mybatis.generator</groupId><artifactId>mybatis-generator-core</artifactId><version>1.3.2</version></dependency>
</dependencies>
创建 MBG 配置⽂件 generatorConfig.xml
1、jdbcConnection 配置数据库连接信息。
2、javaModelGenerator 配置 JavaBean 的⽣成策略。
3、sqlMapGenerator 配置 SQL 映射⽂件⽣成策略。
4、javaClientGenerator 配置 Mapper 接⼝的⽣成策略。
5、table 配置⽬标数据表(tableName:表名,domainObjectName:JavaBean 类名)。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfigurationPUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN""http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration><context id="testTables" targetRuntime="MyBatis3"><jdbcConnectiondriverClass="com.mysql.cj.jdbc.Driver"connectionURL="jdbc:mysql://localhost:3306/mybatis?
useUnicode=true&characterEncoding=UTF-8"userId="root"password="sa"></jdbcConnection><javaModelGenerator targetPackage="nixiang.entity"targetProject="./src/main/java"></javaModelGenerator><sqlMapGenerator targetPackage="nixiang.repository"targetProject="./src/main/java"></sqlMapGenerator><javaClientGenerator type="XMLMAPPER"targetPackage="nixiang.repository" targetProject="./src/main/java"></javaClientGenerator><table tableName="t_user" domainObjectName="User"></table></context>
</generatorConfiguration>
创建 Generator 执⾏类。
package nixiang.test;import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.exception.InvalidConfigurationException;
import org.mybatis.generator.exception.XMLParserException;
import org.mybatis.generator.internal.DefaultShellCallback;
import sun.applet.Main;import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;public class main {public static void main(String[] args) {List<String> warings = new ArrayList<String>();boolean overwrite = true;String genCig = "/generatorConfig.xml";File configFile = new File(Main.class.getResource(genCig).getFile());ConfigurationParser configurationParser = newConfigurationParser(warings);Configuration configuration = null;try {configuration = configurationParser.parseConfiguration(configFile);} catch (IOException e) {e.printStackTrace();} catch (XMLParserException e) {e.printStackTrace();}DefaultShellCallback callback = new DefaultShellCallback(overwrite);MyBatisGenerator myBatisGenerator = null;try {myBatisGenerator = newMyBatisGenerator(configuration,callback,warings);} catch (InvalidConfigurationException e) {e.printStackTrace();}try {myBatisGenerator.generate(null);} catch (SQLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (InterruptedException e) {e.printStackTrace();}}
}
SpringMVC+Mybatis基础知识和配置相关推荐
- ISIS基础知识及配置命令
ISIS基础知识及配置 ISIS原理描述 场景应用 路由计算过程 地址结构 路由器分类 路由器特点 邻居建立过程 DIS及DIS与DR的类比 链路状态信息的载体 链路状态信息的交互 与OSPF的区别 ...
- MyBatis基础知识汇总
文章目录 MyBatis简介 简介 MyBatis历史 为什么要用MyBatis? MyBatis入门 安装 从XML中构建SqlSessionFactory 不使用 XML 构建 SqlSessio ...
- STM32 CubeMx教程 -- 基础知识及配置使用教程
文章目录 前言 一.STM32CubeMx 界面介绍 File 界面 Windows 界面 Help 界面 Updater Settings 界面 二.STM32CubeMx 使用教程 新建工程 配置 ...
- SpringMVC+Mybatis+Maven搭建 简单配置双数据源
POM.xml引包常用的 mybatis 以及 mybatis-spting spring-webmvc log4j spring-jdbc servler-api spring-jdbc < ...
- Spring基础知识和配置
Spring 框架两大核心机制(IoC.AOP) idea运行spring中遇到的问题参考 idea配置遇到的问题 IoC(控制反转)/ DI(依赖注入) AOP(面向切面编程) Spring 是一个 ...
- MyBatis从入门到精通(一)—MyBatis基础知识和快速入门
Mybatis简介 原始jdbc操作(查询数据) Connection connection = null;PreparedStatement preparedStatement = null;Res ...
- Linux系统网络基础知识及配置
一:DNS(domain name system)简介 DNS(Domain Name System,域名系统),因特网上作为域名和IP地址相互映射的一个分布式数据库,能够使用户更方便的访问互联网,而 ...
- MyBatis基础知识概述
一.依赖配置 添加依赖即可,jar包或pom依赖: <dependency><groupId>org.mybatis</groupId><artifactId ...
- 【SpringMVC框架】springmvc的基础知识
1springmvc框架 1.1什么是springmvc springmvc是spring框架的一个模块,springmvc和spring无需通过中间整合层进行整合. springmvc是一个基于mv ...
最新文章
- 赛灵思:人工智能芯片发展方向与误区
- swift_002(Swift的String的基本使用)
- linux中注册系统服务—service命令的原理通俗
- java各种包的用途
- 微博预计要火一阵的SleepSort之Shell及C实现
- 【Java】NIO中Selector的select方法源码分析
- ubuntu18.0.4 不能下载 libgd2-dev(ubuntu 20.04 安装perl 中GD 模块失败的解决办法)
- React 第十二章 React思想
- 基于CUDA的TTI介质逆时偏移与ADCIGs提取
- kalman filter using python
- __init__.py的作用是什么?
- linux /dev/null 中有数据
- 单个form表单内,不同情况显示的不同选项的单选框或多选框的情况下,判断单选框是否存在未选择一个选项情况,并进行提示。
- Geogebra的使用
- Pygame详解(八):locals 模块
- 避坑,在Jetson nano安装编辑openpose
- 2021-07-10 arduino 用于矩阵键盘的 开源库函数 keypad.h使用说明
- Blazor中内置的Open Iconic图标集
- Symantec Liveupdate Administrator的搭建
- “获取硬盘信息失败,请谨慎操作”的解决方案