package com.xyt.springboot.controller;
import com.xyt.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class IndexController {
@Autowired
private UserService userService;
@RequestMapping("/addUser")
public String addUser(String name, int age) {
return userService.addUser(name, age) ? "success" : "fail";
}
}
service接口代码
package com.xyt.springboot.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private JdbcTemplate template;
public Boolean addUser(String name, int age) {
return template.update("insert into users values(null,?,?);", name, age) > 0 ? true : false;
}
}
@SpringBootApplication启动代码
package com.xyt.springboot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AppSpringBoot {
public static void main(String[] args) {
SpringApplication.run(AppSpringBoot.class,args);
}
}
mysql数据库表结构代码
/*
Navicat MySQL Data Transfer
Source Server : 我的本地测试库
Source Server Version : 50540
Source Host : localhost:3306
Source Database : test
Target Server Type : MYSQL
Target Server Version : 50540
File Encoding : 65001
Date: 2019-11-15 14:25:46
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;