啊哈因为很久没有写后端了,写毕设的时候遇到很多雷也忘了很多mybaits的配置
重新搭框之后发现spring真是越来越简洁了……
准备:IDEA,postman测试,数据库mysql
这里的restful可能不全,目前我只做了post和get,想着配点东西给自己测试前端用
我并没有写CRUD……【可能以后会更?
为了方便自己做项目,我把注释用的mybaits的sql那些删掉,直接用mapper.xml了,你想用注释法的话自己google吧
目录
1.新建项目
2.5添加druid(自己找自己加)
3.在resources文件夹里添加yml的配置文件
自行修改数据库的连接
4.参考的目录packge结构
5.5 允许跨域
然后run...
2.添加依赖,后期也可以自己加pom
然后一路next...~
看pom文件
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
yiki.springboot
spring-boot-mybatis
0.0.1-SNAPSHOT
spring-boot-mybatis
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-jdbc
org.springframework.boot
spring-boot-starter-web
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.1
mysql
mysql-connector-java
runtime
com.alibaba
druid
1.1.8
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
spring:
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
initialSize: 5
minIdle: 5
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙,此处是filter修改的地方
filters:
commons-log.connection-logger-name: stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
mybatis:
#如果没有可以不写
#config-location: classpath:mybatisConfig.xml
mapper-locations: classpath:mybatisMappers/*.xml
5.参考代码
bean.user
public class User {
private Integer uid;
private String uname;
private String uemail;
private String upassword;
...
//自行添加get/set
【直接写在了druid.config里了,随便吧~
package com.yiki.config;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import javax.sql.DataSource;
@Configuration
public class DruidConfig extends WebMvcConfigurationSupport {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid() {
return new DruidDataSource();
}
// //druid监控
// //1.配置管理后台的servlet
// @Bean
// public ServletRegistrationBean statViewServlet() {
// ServletRegistrationBean bean =
// new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
// Map initParams = new HashMap<>();
// initParams.put("loginUsername", "admin");
// initParams.put("loginPassword", "admin");
// bean.setInitParameters(initParams);
// return bean;
// }
@Override
protected void addCorsMappings(CorsRegistry registry) {
System.out.println("cors mapping");
//允许全部请求跨域
registry.addMapping("/**")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.allowedOrigins("*");
}
}
mybaits.config
其实没有什么稀奇的..
package com.yiki.config;
import org.apache.ibatis.session.Configuration;
import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;
import org.springframework.context.annotation.Bean;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig {
@Bean
//开启驼峰命名
public ConfigurationCustomizer configurationCustomizer() {
return new ConfigurationCustomizer() {
@Override
public void customize(Configuration configuration) {
configuration.setMapUnderscoreToCamelCase(true);
}
};
}
}
接口mapper
package com.yiki.mapper;
import com.yiki.bean.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface UserMapper {
//增删查改
public User getUserById(Integer uid);
public boolean insertUser(User user);
public List getUsers();
public boolean updateUser(User user);
public boolean deleteUser(int id);
public boolean deleteAllUsers();
public User getUserByNameAndPassword(String uname, String upassword);
}
service类
package com.yiki.Service;
import com.yiki.bean.User;
import com.yiki.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper usermapper;
public boolean addUser(User user) {
return usermapper.insertUser(user);
}
public User authUser(String uname, String upassword) {
try {
return usermapper.getUserByNameAndPassword(uname, upassword);
} catch (Exception e) {
return null;
}
}
public User getUserbyId(Integer uid) {
return usermapper.getUserById(uid);
}
}
controller
package com.yiki.controller;
import com.yiki.Service.UserService;
import com.yiki.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@ResponseBody
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "hello world";
}
@Autowired
private UserService userService;
/*
* x/user/1 GET 根据用户id查询用户数据
x/user POST 新增用户
x/user PUT 修改用户信息
x/user DELETE 删除用户信息*/
@GetMapping("/user/{uid}")
public User getxmlUser(@PathVariable("uid") Integer id) {
return userService.getUserbyId(id);
}
@PostMapping("/user")
public int registeUser(@RequestBody User user) {
boolean res = userService.addUser(user);
if (res) {
return 1;
}
return 0;
}
@PostMapping("/authUser")
public User authUser(@RequestBody User user) {
System.out.println(user.getUname());
User res = userService.authUser(user.getUname(), user.getUpassword());
if (res != null) {
return user;
}
return null;
}
}
insert into user(uname, uemail,upassword)
values(#{uname}, #{uemail},#{upassword})
不报错就代表你get了
如果是post
postman