欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Spring 下 MyBatis 的基本使用

程序员文章站 2022-05-20 18:02:04
参看代码 GitHub : pom.xml dbconfig.properties DbConfig.java MySqlBean.java User.java UserMapper.java UserDynaSqlProvider.java UserService.java UserService ......

参看代码 GitHub :

pom.xml

dbconfig.properties

DbConfig.java

MySqlBean.java

User.java

UserMapper.java

UserDynaSqlProvider.java

UserService.java

UserServiceImpl.java

MyBatisController.java

mybatis.jsp  

一、引入类库

 1         <!-- mybatis核心包 -->
 2         <dependency>
 3             <groupId>org.mybatis</groupId>
 4             <artifactId>mybatis</artifactId>
 5         </dependency>
 6         <!--mybatis spring 插件 -->
 7         <dependency>
 8             <groupId>org.mybatis</groupId>
 9             <artifactId>mybatis-spring</artifactId>
10         </dependency>
11         <!-- Mysql数据库驱动包 -->
12         <dependency>
13             <groupId>mysql</groupId>
14             <artifactId>mysql-connector-java</artifactId>
15         </dependency>
16         <!-- connection pool -->
17         <dependency>
18             <groupId>com.alibaba</groupId>
19             <artifactId>druid</artifactId>
20             <!--<scope>runtime</scope>-->
21         </dependency>

二、DB 与 Pool 的配置

 1 #MySQL
 2 jdbc.driver=com.mysql.jdbc.Driver
 3 
 4 #基本属性 url、user、password
 5 jdbc.url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true
 6 jdbc.username=root
 7 jdbc.password=liumeng
 8 
 9 #配置初始化大小、最小、最大
10 jdbc.initialSize=1
11 jdbc.minIdle=1
12 jdbc.maxActive=20
13 
14 #配置获取连接等待超时的时间
15 jdbc.maxWait=60000
16 
17 #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
18 jdbc.timeBetweenEvictionRunsMillis=60000
19 
20 #配置一个连接在池中最小生存的时间,单位是毫秒
21 jdbc.minEvictableIdleTimeMillis=300000
22 
23 jdbc.validationQuery=SELECT 'x'
24 jdbc.testWhileIdle=true
25 jdbc.testOnBorrow=false
26 jdbc.testOnReturn=false
27 
28 #打开PSCache,并且指定每个连接上PSCache的大小
29 jdbc.poolPreparedStatements=false
30 jdbc.maxPoolPreparedStatementPerConnectionSize=20
31 
32 #配置监控统计拦截的filters
33 jdbc.filters=stat

 三、Bean 的 配置

  1.配置属性到bean

  1 package lm.solution.web.config.properties;
  2 
  3 import org.springframework.beans.factory.annotation.Value;
  4 import org.springframework.context.annotation.AnnotationConfigApplicationContext;
  5 import org.springframework.context.annotation.PropertySource;
  6 import org.springframework.stereotype.Component;
  7 
  8 @Component(value = "dbConfig")
  9 @PropertySource("classpath:dbconfig.properties")
 10 public class DbConfig {
 11 
 12     @Value("${jdbc.url}")
 13     private String url;
 14     public String getUrl(){
 15         return this.url;
 16     }
 17 
 18     @Value("${jdbc.username}")
 19     private String username;
 20     public String getUsername(){
 21         return this.username;
 22     }
 23 
 24     @Value("${jdbc.password}")
 25     private String password;
 26     public String getPassword(){
 27         return this.password;
 28     }
 29 
 30     @Value("${jdbc.initialSize}")
 31     private Integer initialSize;
 32     public Integer getInitialSize(){
 33         return this.initialSize;
 34     }
 35 
 36     @Value("${jdbc.minIdle}")
 37     private Integer minIdle;
 38     public Integer getMinIdle(){
 39         return this.minIdle;
 40     }
 41 
 42     @Value("${jdbc.maxActive}")
 43     private Integer maxActive;
 44     public Integer getMaxActive(){
 45         return this.maxActive;
 46     }
 47 
 48     @Value("${jdbc.maxWait}")
 49     private Long maxWait;
 50     public Long getMaxWait() {
 51         return this.maxWait;
 52     }
 53 
 54     @Value("${jdbc.timeBetweenEvictionRunsMillis}")
 55     private Long timeBetweenEvictionRunsMillis;
 56     public Long getTimeBetweenEvictionRunsMillis(){
 57         return this.timeBetweenEvictionRunsMillis;
 58     }
 59 
 60     @Value("${jdbc.minEvictableIdleTimeMillis}")
 61     private Long minEvictableIdleTimeMillis;
 62     public Long getMinEvictableIdleTimeMillis(){
 63         return this.minEvictableIdleTimeMillis;
 64     }
 65 
 66     @Value("${jdbc.validationQuery}")
 67     private String validationQuery;
 68     public String getValidationQuery(){
 69         return this.validationQuery;
 70     }
 71 
 72     @Value("${jdbc.testWhileIdle}")
 73     private Boolean testWhileIdle;
 74     public Boolean getTestWhileIdle(){
 75         return this.testWhileIdle;
 76     }
 77 
 78     @Value("${jdbc.testOnBorrow}")
 79     private Boolean testOnBorrow;
 80     public Boolean getTestOnBorrow(){
 81         return this.testOnBorrow;
 82     }
 83 
 84     @Value("${jdbc.testOnReturn}")
 85     private Boolean testOnReturn;
 86     public Boolean getTestOnReturn(){
 87         return this.testOnReturn;
 88     }
 89 
 90     @Value("${jdbc.poolPreparedStatements}")
 91     private Boolean poolPreparedStatements;
 92     public Boolean getPoolPreparedStatements(){
 93         return this.poolPreparedStatements;
 94     }
 95 
 96     @Value("${jdbc.maxPoolPreparedStatementPerConnectionSize}")
 97     private Integer maxPoolPreparedStatementPerConnectionSize;
 98     public Integer getMaxPoolPreparedStatementPerConnectionSize(){
 99         return this.maxPoolPreparedStatementPerConnectionSize;
100     }
101 
102     @Value("${jdbc.filters}")
103     private String filters;
104     public String getFilters(){
105         return this.filters;
106     }
107 
108     private final static Object object=new Object();
109     private static DbConfig config;
110     public static DbConfig getConfig(){
111         return config;
112     }
113 
114     static {
115         synchronized(object) {
116             AnnotationConfigApplicationContext configContext = new AnnotationConfigApplicationContext(DbConfig.class);
117             config = (DbConfig) configContext.getBean("dbConfig");
118         }
119     }
120 
121 
122 }

  2.配置组件 Bean

 1 package lm.solution.web.config.beans;
 2 
 3 import com.alibaba.druid.pool.DruidDataSource;
 4 import lm.solution.web.config.properties.DbConfig;
 5 import org.mybatis.spring.SqlSessionFactoryBean;
 6 import org.mybatis.spring.mapper.MapperScannerConfigurer;
 7 import org.springframework.context.annotation.Bean;
 8 import org.springframework.context.annotation.Configuration;
 9 import org.springframework.jdbc.datasource.DataSourceTransactionManager;
10 
11 import java.sql.SQLException;
12 
13 @Configuration
14 public class MySqlBean {
15 
16     // dataSource 配置数据源
17     @Bean(
18             name = "dataSource",
19             initMethod = "init",
20             destroyMethod = "close"
21     )
22     public DruidDataSource druidDataSource(){
23 
24         try {
25 
26             //
27             DbConfig db=DbConfig.getConfig();
28 
29             //
30             DruidDataSource dataSource = new DruidDataSource();
31             dataSource.setUrl(db.getUrl());
32             dataSource.setUsername(db.getUsername());
33             dataSource.setPassword(db.getPassword());
34             dataSource.setInitialSize(db.getInitialSize());
35             dataSource.setMinIdle(db.getMinIdle());
36             dataSource.setMaxActive(db.getMaxActive());
37             dataSource.setMaxWait(db.getMaxWait());
38             dataSource.setTimeBetweenEvictionRunsMillis(db.getTimeBetweenEvictionRunsMillis());
39             dataSource.setMinEvictableIdleTimeMillis(db.getMinEvictableIdleTimeMillis());
40             dataSource.setValidationQuery(db.getValidationQuery());
41             dataSource.setTestWhileIdle(db.getTestWhileIdle());
42             dataSource.setTestOnBorrow(db.getTestOnBorrow());
43             dataSource.setTestOnReturn(db.getTestOnReturn());
44             dataSource.setPoolPreparedStatements(db.getPoolPreparedStatements());
45             dataSource.setMaxPoolPreparedStatementPerConnectionSize(db.getMaxPoolPreparedStatementPerConnectionSize());
46             dataSource.setFilters(db.getFilters());
47             return dataSource;
48 
49         }catch (SQLException se){
50             se.printStackTrace();
51         }
52 
53         return null;
54 
55     }
56 
57     // mybatis和spring完美整合,不需要mybatis的配置映射文件
58     @Bean(name = "sqlSessionFactory")
59     public SqlSessionFactoryBean sqlSessionFactoryBean(DruidDataSource dataSource){
60 
61         SqlSessionFactoryBean factory=new SqlSessionFactoryBean();
62         factory.setDataSource(dataSource);
63         return factory;
64 
65     }
66 
67     // DAO接口所在包名,Spring会自动查找其下的类
68     @Bean
69     public MapperScannerConfigurer mapperScannerConfigurer(){
70 
71         MapperScannerConfigurer scannerConfigurer=new MapperScannerConfigurer();
72         scannerConfigurer.setBasePackage("lm.solution.mapper");
73         scannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
74         return scannerConfigurer;
75 
76     }
77 
78     // 对dataSource 数据源进行事务管理
79     @Bean(name = "transactionManager")
80     public DataSourceTransactionManager dataSourceTransactionManager( DruidDataSource dataSource ){
81 
82         DataSourceTransactionManager transactionManager=new DataSourceTransactionManager();
83         transactionManager.setDataSource(dataSource);
84         return transactionManager;
85 
86     }
87 
88 
89 
90 }

四、操作 mysql 数据库 -- 简单的CRUD

  1. 实体

 1 package lm.solution.pojo.entity;
 2 
 3 public class User {
 4     private Integer id;
 5 
 6     private String name;
 7 
 8     private String age;
 9 
10     private Integer salary;
11 
12     public Integer getId() {
13         return id;
14     }
15 
16     public void setId(Integer id) {
17         this.id = id;
18     }
19 
20     public String getName() {
21         return name;
22     }
23 
24     public void setName(String name) {
25         this.name = name == null ? null : name.trim();
26     }
27 
28     public String getAge() {
29         return age;
30     }
31 
32     public void setAge(String age) {
33         this.age = age == null ? null : age.trim();
34     }
35 
36     public Integer getSalary() {
37         return salary;
38     }
39 
40     public void setSalary(Integer salary) {
41         this.salary = salary;
42     }
43 }

  2.MyBatis Mapper

 1 package lm.solution.mapper;
 2 
 3 import lm.solution.pojo.entity.User;
 4 import lm.solution.mapper.provider.UserDynaSqlProvider;
 5 import org.apache.ibatis.annotations.*;
 6 
 7 import java.util.List;
 8 
 9 public interface UserMapper {
10 
11     @Select(" select * from user ")
12     List<User> findAllUsers();
13 
14     @Select(" select * from user where id=#{id} ")
15     User findById(long id);
16 
17     @Select(" select * from user where name=#{name} ")
18     User findByName(String name);
19 
20     @InsertProvider(type= UserDynaSqlProvider.class,method = "saveUser")
21     @Options(useGeneratedKeys = true,keyColumn = "id")
22     Integer saveUser(User user);
23 
24     @UpdateProvider(type = UserDynaSqlProvider.class,method = "updateUser")
25     Integer updateUser(User user);
26 
27     @Delete(" delete from user where id=#{id} ")
28     Integer deleteUser(long id);
29 
30     @Delete(" delete from user where 1=1 ")
31     Integer deleteAllUsers();
32 }
 1 package lm.solution.mapper.provider;
 2 
 3 import lm.solution.pojo.entity.User;
 4 import org.apache.ibatis.jdbc.SQL;
 5 
 6 public class UserDynaSqlProvider {
 7 
 8 
 9     public String saveUser(final User user) {
10         return new SQL() {
11             {
12                 INSERT_INTO("user");
13                 if(user.getName()!=null&&!"".equals(user.getName())){
14                     VALUES("name","#{name}");
15                 }
16                 if(user.getAge()!=null&&!"".equals(user.getAge())){
17                     VALUES("age","#{age}");
18                 }
19                 if(user.getSalary()!=null){
20                     VALUES("salary","#{salary}");
21                 }
22             }
23         }.toString();
24     }
25 
26     public String updateUser(final User user){
27         return  new SQL(){
28             {
29                 UPDATE("user");
30                 if(user.getName()!=null && !"".equals(user.getName())){
31                     SET(" name=#{name} ");
32                 }
33                 if(user.getAge()!=null && !"".equals(user.getAge())){
34                     SET(" age=#{age} ");
35                 }
36                 if(user.getSalary()!=null){
37                     SET(" salary=#{salary} ");
38                 }
39                 WHERE(" id=#{id} ");
40             }
41         }.toString();
42     }
43 
44 
45 }

  3.Service 

 1 package lm.solution.service.mysql;
 2 
 3 import lm.solution.pojo.entity.User;
 4 import java.util.List;
 5 
 6 public interface UserService {
 7 
 8     List<User> findAllUsers();
 9 
10     User findById(long id);
11 
12     boolean isUserExist(User user);
13 
14     void saveUser(User user);
15 
16     void updateUser(User user);
17 
18     void deleteUser(long id);
19 
20     void deleteAllUsers();
21 
22 }
 1 package lm.solution.service.mysql.impl;
 2 
 3 import lm.solution.pojo.entity.User;
 4 import lm.solution.mapper.UserMapper;
 5 import lm.solution.service.mysql.UserService;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.stereotype.Service;
 8 import org.springframework.transaction.annotation.Transactional;
 9 import org.springframework.transaction.annotation.Propagation;
10 import org.springframework.transaction.annotation.Isolation;
11 import java.util.List;
12 
13 @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT)
14 @Service("userService")
15 public class UserServiceImpl implements UserService {
16 
17     @Autowired
18     private UserMapper userMapper;
19 
20 
21     @Override
22     public List<User> findAllUsers() {
23         return userMapper.findAllUsers();
24         //return null;
25     }
26 
27     @Override
28     public User findById(long id) {
29         //return null;
30 
31         return userMapper.findById(id);
32     }
33 
34     @Override
35     public boolean isUserExist(User user) {
36 
37         User userDB=userMapper.findByName(user.getName());
38         if(userDB==null){
39             return  false;
40         }else {
41             return true;
42         }
43     }
44 
45     @Override
46     public void saveUser(User user) {
47         userMapper.saveUser(user);
48     }
49 
50     @Override
51     public void updateUser(User user) {
52         userMapper.updateUser(user);
53     }
54 
55     @Override
56     public void deleteUser(long id) {
57         userMapper.deleteUser(id);
58     }
59 
60     @Override
61     public void deleteAllUsers() {
62         userMapper.deleteAllUsers();
63     }
64 
65 
66 }

  4.Controller

  1 package lm.solution.web.controller.db;
  2 
  3 import com.fasterxml.jackson.core.JsonProcessingException;
  4 import com.fasterxml.jackson.databind.ObjectMapper;
  5 import lm.solution.pojo.entity.User;
  6 import lm.solution.service.mysql.UserService;
  7 import org.springframework.beans.factory.annotation.Autowired;
  8 import org.springframework.beans.factory.annotation.Qualifier;
  9 import org.springframework.stereotype.Controller;
 10 import org.springframework.web.bind.annotation.*;
 11 
 12 import java.io.IOException;
 13 import java.util.List;
 14 
 15 @Controller
 16 public class MyBatisController {
 17 
 18     private static ObjectMapper objectMapper;
 19 
 20     @Autowired
 21     @Qualifier("userService")
 22     private UserService userService;
 23 
 24     static {
 25         objectMapper = new ObjectMapper();
 26     }
 27 
 28     @RequestMapping(
 29             value = "/mybatis/userall",
 30             method = RequestMethod.GET,
 31             produces = {"application/json;charset=UTF-8"})
 32     @ResponseBody
 33     public String allUsers() {
 34 
 35         try {
 36             List<User> users = userService.findAllUsers();
 37             return objectMapper.writeValueAsString(users);
 38         } catch (IOException ioe) {
 39             ioe.printStackTrace();
 40             return "{}";
 41         }
 42 
 43     }
 44 
 45     @RequestMapping(
 46             value = "/mybatis/{id}",
 47             method = RequestMethod.GET,
 48             produces = {"application/json;charset=UTF-8"})
 49     @ResponseBody
 50     public String getUserById(@PathVariable("id") long id) {
 51 
 52         try {
 53             User user = userService.findById(id);
 54             return objectMapper.writeValueAsString(user);
 55         } catch (IOException ioe) {
 56             ioe.printStackTrace();
 57             return "{}";
 58         }
 59     }
 60 
 61     @RequestMapping(
 62             value = "/mybatis/create",
 63             method = RequestMethod.POST,
 64             consumes = {"application/json"},
 65             produces = {"application/json;charset=UTF-8"})
 66     @ResponseBody
 67     public String create(@RequestBody User user) {
 68 
 69         try {
 70 
 71             userService.saveUser(user);
 72             return objectMapper.writeValueAsString(user);
 73 
 74         }catch (JsonProcessingException jpe){
 75             jpe.printStackTrace();
 76         }
 77 
 78         return "{}";
 79 
 80     }
 81 
 82     @RequestMapping(
 83             value = "/mybatis/update",
 84             method = RequestMethod.PUT,
 85             consumes = {"application/json"},
 86             produces = {"application/json;charset=UTF-8"})
 87     @ResponseBody
 88     public String update(@RequestBody User user) {
 89 
 90         try {
 91 
 92             userService.updateUser(user);
 93             return objectMapper.writeValueAsString(user);
 94 
 95         }catch (JsonProcessingException jpe){
 96             jpe.printStackTrace();
 97         }
 98 
 99         return "{}";
100 
101     }
102 
103     @RequestMapping(
104             value = "/mybatis/{id}",
105             method = RequestMethod.DELETE,
106             produces = {"application/json;charset=UTF-8"})
107     @ResponseBody
108     public String deleteById(@PathVariable("id") long id) {
109         userService.deleteUser(id);
110         return "success";
111 
112     }
113 
114     @RequestMapping(
115             value = "/mybatis",
116             method = RequestMethod.DELETE,
117             produces = {"application/json;charset=UTF-8"})
118     @ResponseBody
119     public String deleteAll() {
120         userService.deleteAllUsers();
121         return "success";
122 
123     }
124 
125 }

  5.View

  1 <%--
  2   Created by IntelliJ IDEA.
  3   User: liumeng
  4   Date: 2018/3/2
  5   Time: 14:25
  6   To change this template use File | Settings | File Templates.
  7 --%>
  8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  9 <html>
 10 <head>
 11     <title>MySQL op by MyBatis</title>
 12     <script src="/assets/js/jquery-3.3.1.js"></script>
 13 </head>
 14 <body>
 15 <p>
 16     <button id="btnAllusers">GET-查看所有</button>
 17     <br>
 18 <div id="getAllusers"></div>
 19 <br>
 20 <script>
 21     $(function () {
 22         $('#btnAllusers').on("click", function (e) {
 23             var request = $.ajax({
 24                 url: "/mybatis/userall",
 25                 method: "GET"
 26             });
 27 
 28             request.done(function (data) {
 29                 if (data) {
 30                     var html = "";
 31                     for (var i = 0; i < data.length; i++) {
 32                         html += "<span>id</sapn>:<span>" + data[i].id + "</span><br>";
 33                         html += "<span>name</sapn>:<span>" + data[i].name + "</span><br>";
 34                         html += "<span>age</sapn>:<span>" + data[i].age + "</span><br>";
 35                         html += "<span>salary</sapn>:<span>" + data[i].salary + "</span><br>";
 36                         html += "<br>----------------------------------------------------------<br>";
 37                     }
 38                     $("#getAllusers").html(html);
 39                 }
 40             });
 41 
 42             request.fail(function (jqXHR, textStatus) {
 43                 alert("Request failed: " + textStatus);
 44             });
 45         });
 46     });
 47 </script>
 48 <hr>
 49 <button id="btnUserByID">GET-查看ByID</button>
 50 <br>
 51 <span>ID:</span><input type="text" id="userbyIDtx">
 52 <br>
 53 <div id="UserByID"></div>
 54 <br>
 55 <script>
 56     $(function () {
 57         $('#btnUserByID').on("click", function (e) {
 58             var request = $.ajax({
 59                 url: "/mybatis/"+$("#userbyIDtx").val(),
 60                 method: "GET",
 61                 dataType:"json"
 62             });
 63 
 64             request.done(function (data) {
 65                 if (data) {
 66                     var html = "";
 67                     html += "<span>id</sapn>:<span>" + data.id + "</span><br>";
 68                     html += "<span>name</sapn>:<span>" + data.name + "</span><br>";
 69                     html += "<span>age</sapn>:<span>" + data.age + "</span><br>";
 70                     html += "<span>salary</sapn>:<span>" + data.salary + "</span><br>";
 71                     html += "<br>----------------------------------------------------------<br>";
 72                     $("#UserByID").html(html);
 73                 }
 74             });
 75 
 76             request.fail(function (jqXHR, textStatus) {
 77                 alert("Request failed: " + textStatus);
 78             });
 79         });
 80     });
 81 </script>
 82 <hr>
 83 <button id="createOne">POST-创建一个</button>
 84 <br>
 85 <span>ID:</span><input type="text" disabled="disabled" ><br>
 86 <span>Name:</span><input type="text" id="createName" ><br>
 87 <span>Age:</span><input type="text" id="createAge" ><br>
 88 <span>Salary:</span><input type="text" id="createSalary" >
 89 <br>
 90 <div id="createUser"></div>
 91 <br>
 92 <script>
 93     $(function () {
 94         $('#createOne').on("click", function (e) {
 95             var data={
 96                 name:$("#createName").val(),
 97                 age:$("#createAge").val(),
 98                 salary:$("#createSalary").val()
 99             };
100 
101             var request = $.ajax({
102                 url: "/mybatis/create",
103                 method: "POST",
104                 data:JSON.stringify(data),
105                 contentType:"application/json"
106                 //dataType:"json"
107             });
108 
109             request.done(function (data) {
110                 if (data) {
111                     var html = "";
112                     html += "<span>id</sapn>:<span>" + data.id + "</span><br>";
113                     html += "<span>name</sapn>:<span>" + data.name + "</span><br>";
114                     html += "<span>age</sapn>:<span>" + data.age + "</span><br>";
115                     html += "<span>salary</sapn>:<span>" + data.salary + "</span><br>";
116                     html += "<br>----------------------------------------------------------<br>";
117                     $("#createUser").html(html);
118                 }
119             });
120 
121             request.fail(function (jqXHR, textStatus) {
122                 alert("Request failed: " + textStatus);
123             });
124         });
125     });
126 </script>
127 <hr>
128 <button id="putOne">PUT-更新一个</button>
129 <br>
130 <span>ID:</span><input type="text" id="putId" ><br>
131 <span>Name:</span><input type="text" id="putName" ><br>
132 <span>Age:</span><input type="text" id="putAge" ><br>
133 <span>Salary:</span><input type="text" id="putSalary" >
134 <br>
135 <div id="putUser"></div>
136 <br>
137 <script>
138     $(function () {
139         $('#putOne').on("click", function (e) {
140             var data={
141                 id:$("#putId").val(),
142                 name:$("#putName").val(),
143                 age:$("#putAge").val(),
144                 salary:$("#putSalary").val()
145             };
146 
147             var request = $.ajax({
148                 url: "/mybatis/update",
149                 method: "PUT",
150                 data:JSON.stringify(data),
151                 contentType:"application/json"
152                 //dataType:"json"
153             });
154 
155             request.done(function (data) {
156                 if (data) {
157                     var html = "";
158                     html += "<span>id</sapn>:<span>" + data.id + "</span><br>";
159                     html += "<span>name</sapn>:<span>" + data.name + "</span><br>";
160                     html += "<span>age</sapn>:<span>" + data.age + "</span><br>";
161                     html += "<span>salary</sapn>:<span>" + data.salary + "</span><br>";
162                     html += "<br>----------------------------------------------------------<br>";
163                     $("#createUser").html(html);
164                 }
165             });
166 
167             request.fail(function (jqXHR, textStatus) {
168                 alert("Request failed: " + textStatus);
169             });
170         });
171     });
172 </script>
173 <hr>
174 <button id="deleteOne">DELETE-删除一个</button>
175 <br>
176 <span>ID:</span><input type="text" id="deleteId" ><br>
177 <!--<span>Name:</span><input type="text" id="putName" ><br>
178 <span>Age:</span><input type="text" id="putAge" ><br>
179 <span>Salary:</span><input type="text" id="putSalary" >-->
180 <br>
181 <div id="deleteUser"></div>
182 <br>
183 <script>
184     $(function () {
185         $('#deleteOne').on("click", function (e) {
186             // var data={
187             //     id:$("#putId").val(),
188             //     name:$("#putName").val(),
189             //     age:$("#putAge").val(),
190             //     salary:$("#putSalary").val()
191             // };
192 
193             var request = $.ajax({
194                 url: "/mybatis/"+$("#deleteId").val(),
195                 method: "DELETE",
196                 // data:JSON.stringify(data),
197                 contentType:"application/json"
198                 //dataType:"json"
199             });
200 
201             request.done(function (data) {
202                 if (data) {
203                     var html = "";
204                     // html += "<span>id</sapn>:<span>" + data.id + "</span><br>";
205                     // html += "<span>name</sapn>:<span>" + data.name + "</span><br>";
206                     // html += "<span>age</sapn>:<span>" + data.age + "</span><br>";
207                     // html += "<span>salary</sapn>:<span>" + data.salary + "</span><br>";
208                     // html += "<br>----------------------------------------------------------<br>";
209                     $("#createUser").html(data);
210                 }
211             });
212 
213             request.fail(function (jqXHR, textStatus) {
214                 alert("Request failed: " + textStatus);
215             });
216         });
217     });
218 </script>
219 <hr>
220 <button id="deleteAll">DELETE-删除所有</button>
221 <br>
222 <div id="deleteUserAll"></div>
223 <br>
224 <script>
225     $(function () {
226         $('#deleteAll').on("click", function (e) {
227             var request = $.ajax({
228                 url: "/mybatis",
229                 method: "DELETE",
230                 // data:JSON.stringify(data),
231                 contentType:"application/json"
232                 //dataType:"json"
233             });
234 
235             request.done(function (data) {
236                 if (data) {
237                     var html = "";
238                     // html += "<span>id</sapn>:<span>" + data.id + "</span><br>";
239                     // html += "<span>name</sapn>:<span>" + data.name + "</span><br>";
240                     // html += "<span>age</sapn>:<span>" + data.age + "</span><br>";
241                     // html += "<span>salary</sapn>:<span>" + data.salary + "</span><br>";
242                     // html += "<br>----------------------------------------------------------<br>";
243                     $("#deleteUserAll").html(data);
244                 }
245             });
246 
247             request.fail(function (jqXHR, textStatus) {
248                 alert("Request failed: " + textStatus);
249             });
250         });
251     });
252 </script>
253 <hr>
254 </p>
255 </body>
256 </html>

 

  

 

 


                                         蒙

                                    2018-05-08 00:15 周二