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.xsd
       http://www.springframework.org/schema/mvc
       http://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 {

    @Autowired
    private 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));
    }

    @Override
    public Collection<Student> findAll() {
        return studentMap.values();
    }

    @Override
    public Student findById(long id) {
        return studentMap.get(id);
    }

    @Override
    public void saveOrUpdate(Student student) {
        studentMap.put(student.getId(),student);
    }

    @Override
    public 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&amp;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 generatorConfiguration
        PUBLIC "-//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">
        <jdbcConnection
                driverClass="com.mysql.cj.jdbc.Driver"
                connectionURL="jdbc:mysql://localhost:3306/mybatis?
useUnicode=true&amp;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 = new
                ConfigurationParser(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 = new
                    MyBatisGenerator(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();
        }
    }
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值