SpringMVC和Mybatis简单的记录一下,因为现在有比较新的SpringBoot和Mybatis plus简化了很多步骤。
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.0.11.RELEASEversion>
dependency>
dependencies>
<web-app>
<display-name>Archetype Created Web Applicationdisplay-name>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
<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>
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";
}
}
REST:Representational State Transfer,资源表现层状态转换,是目前比较主流的一种互联网软件架构,它结构清晰、标准规范、易于理解、便于扩展。
网络上的一个实体,或者说网络中存在的一个具体信息,一段文本、一张图片、一首歌曲、一段视频等等,总之就是一个具体的存在。可以用一个 URI(统一资源定位符)指向它,每个资源都有对应的一个特定的 URI,要获取该资源时,只需要访问对应的 URI 即可。
资源具体呈现出来的形式,比如文本可以用 txt 格式表示,也可以用 HTML、XML、JSON等格式来表示。
客户端如果希望操作服务器中的某个资源,就需要通过某种方式让服务端发生状态转换,而这种转换是建立在表现层之上的,所有叫做"表现层状态转换"。
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
ORMapping: Object Relationship Mapping 对象关系映射
对象指⾯向对象
关系指关系型数据库
Java 到 MySQL 的映射,开发者可以以⾯向对象的思想来管理数据库。
新建 Maven ⼯程,pom.xml
<dependencies>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.11version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<version>1.18.6version>
<scope>providedscope>
dependency>
dependencies> <build>
<resources>
<resource>
<directory>src/main/javadirectory>
<includes>
<include>**/*.xmlinclude>
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,⽂件名可⾃定义
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC">transactionManager>
<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 和接⼝中对应⽅法的返回值类型⼀致。
<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
<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 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.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.5version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>8.0.11version>
dependency>
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.3.2version>
dependency>
dependencies>
创建 MBG 配置⽂件 generatorConfig.xml
1、jdbcConnection 配置数据库连接信息。
2、javaModelGenerator 配置 JavaBean 的⽣成策略。
3、sqlMapGenerator 配置 SQL 映射⽂件⽣成策略。
4、javaClientGenerator 配置 Mapper 接⼝的⽣成策略。
5、table 配置⽬标数据表(tableName:表名,domainObjectName:JavaBean 类名)。
<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<jdbcConnection
driverClass="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 = 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();
}
}
}