您的位置:首页 > 编程语言 > Java开发

前后端分离之SpringBoot2.x整合mybatis实现数据库的增删改查操作(二)

2019-04-28 22:18 986 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/qq_42338771/article/details/89647257

1.由于是前后端分离架构,因此会产生跨域问题,至于为何会产生跨域问题,自行百度,这里不多说

跨域问题解决方案

package com.example.demo1.corsConfig;
//设置服务器允许跨域访问
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyConfiguration extends WebMvcConfigurerAdapter  {

@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowCredentials(true)
.allowedHeaders("*")
.allowedOrigins("*")
.allowedMethods("*");

}
}

2.json字符串转换工具类实现

package com.example.demo1.utils;

import java.io.IOException;

import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {

private static ObjectMapper objectMapper = new ObjectMapper();

//对象转字符串
public static <T> String obj2String(T obj){
if (obj == null){
return null;
}
try {
return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

//字符串转对象
public static <T> T string2Obj(String str,Class<T> clazz){
if (StringUtils.isEmpty(str) || clazz == null){
return null;
}
try {
return clazz.equals(String.class)? (T) str :objectMapper.readValue(str,clazz);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

3.数据库配置

spring.datasource.driver-class-name =com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8
spring.datasource.username =root  //填入自己的用户名
spring.datasource.password =123456 //填入自己的密码
#spring.datasource.type =com.alibaba.druid.pool.DruidDataSource
logging.level.com.example.demo1.mapper=debug

4.用postman进行接口测试
数据库数据

通过名称查询单个数据

查询所有

github源码地址

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐