搞了两天了,这个错误还是没有解决?
1、在测试ShopService时,可以正常插入数据数据
public class ShopServiceTest extends BaseTest {
@Resource
private ShopService shopService;
@Test
public void testAddShop() throws FileNotFoundException {
Shop shop = new Shop();
Person person = new Person();
person.setUserId(1L);
ShopCategory shopCategory = new ShopCategory();
shopCategory.setShopCategoryId(7L);
Area area = new Area();
area.setAreaId(2);
shop.setShopName("咖啡馆");
shop.setShopDesc("test2");
shop.setShopAddress("test2");
shop.setShopPhone("test2");
shop.setPriority(0);
shop.setAdvice("审核中");
shop.setEnableStatus(ShopStateEnum.CHECK.getState());
shop.setCreateTime(new Date());
shop.setLastEditTime(new Date());
shop.setOwner(person);
shop.setShopCategory(shopCategory);
shop.setArea(area);
File shopImg = new File("C:/Users/CD4356/Desktop/1.jpg");
InputStream input = new FileInputStream(shopImg);
ShopExecution shopExecution = shopService.addShop(shop,input,shopImg.getName());
assertEquals(ShopStateEnum.CHECK.getState(),shopExecution.getState());
}
}
-----------------------------------------------------------------------------------------------------------------
2、但在前端点击提交按钮的时候,就报下面这个错了,我看了几十遍代码了,都还是发现找不到到底是哪里出错了,打断点测试也测试不出来,(百度说这是外键关联问题,但我在测试ShopService的时候是可以插入数据的)
错误信息:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.RuntimeException: addShop error: ### Error updating database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`o2o`.`shop`, CONSTRAINT `fk_area_id` FOREIGN KEY (`area_id`) REFERENCES `area` (`area_id`)) ### The error may exist in file [D:\tomcat\apache-tomcat-9.0.16\webapps\o2o\WEB-INF\classes\mapper\ShopDao.xml] ### The error may involve com.cd.store.dao.ShopDao.insertShop-Inline ### The error occurred while setting parameters ### SQL: insert into shop(shop_name,shop_desc,shop_address,shop_phone,shop_img,priority,advice,enable_status, create_time,last_edit_time,owner_id,shop_category_id,area_id) values (?,?,?,?,?,?,?,?, ?,?,?,?,?) ### Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`o2o`.`shop`, CONSTRAINT `fk_area_id` FOREIGN KEY (`area_id`) REFERENCES `area` (`area_id`)) ; SQL []; Cannot add or update a child row: a foreign key constraint fails (`o2o`.`shop`, CONSTRAINT `fk_area_id` FOREIGN KEY (`area_id`) REFERENCES `area` (`area_id`)); nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`o2o`.`shop`, CONSTRAINT `fk_area_id` FOREIGN KEY (`area_id`) REFERENCES `area` (`area_id`)) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) javax.servlet.http.HttpServlet.service(HttpServlet.java:660) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) javax.servlet.http.HttpServlet.service(HttpServlet.java:741) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
--
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cd.store.dao.ShopDao">
<insert id="insertShop" useGeneratedKeys="true" keyColumn="shop_id" keyProperty="shopId" parameterType="Shop">
insert into shop(shop_name,shop_desc,shop_address,shop_phone,shop_img,priority,advice,enable_status,
create_time,last_edit_time,owner_id,shop_category_id,area_id)
values
(#{shopName},#{shopDesc},#{shopAddress},#{shopPhone},#{shopImg},#{priority},#{advice},#{enableStatus},
#{createTime},#{lastEditTime},#{owner.userId},#{shopCategory.shopCategoryId},#{area.areaId})
</insert>
<update id="updateShop" parameterType="Shop">
update shop
<set>
<if test="shopName != null">shop_name=#{shopName},</if>
<if test="shopDesc != null">shop_desc=#{shopDesc},</if>
<if test="shopAddress != null">shop_address=#{shopAddress},</if>
<if test="shopPhone != null">shop_phone=#{shopPhone},</if>
<if test="shopImg != null">shop_img=#{shopImg},</if>
<if test="priority != null">priority=#{priority},</if>
<if test="advice != null">advice=#{advice},</if>
<if test="enableStatus != null">enable_status=#{enableStatus},</if>
<if test="createTime != null">create_time=#{createTime},</if>
<if test="lastEditTime != null">last_edit_time=#{lastEditTime},</if>
<if test="shopCategory != null">shop_category_id=#{shopCategory.shopCategoryId},</if>
<if test="area != null">area_id=#{area.areaId}</if>
</set>
where shop_id=#{shopId}
</update>
</mapper>--
public class PathUtil {
//获取文件分隔符
private static String separator = System.getProperty("file.separator");
public static String getImgBasePath(){
//获取系统名称
String os = System.getProperty("os.name");
String basePath = "";
if(os.toLowerCase().startsWith("win")){
basePath = "D:/idea/java_workspace/image/";
}else {
basePath = "home/shop/image/";
}
basePath = basePath.replace("/",separator);
return basePath;
}
public static String getShopImagePath(Long shopId){
String imagePath = "upload/shop/"+ shopId +"/";
return imagePath.replace("/",separator);
}
}--
public class ImageUtil {
//类路径资源目录
private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
//时间格式
private static SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
//随机类
private static Random random = new Random();
/**
* 将CommonsMultiFile转化成File
* @param file
* @return
*/
public static File transferCommonsMultipartFileToFile(CommonsMultipartFile file){
//创建File文件对象
File newFile = new File(file.getOriginalFilename());
try {
//将传入文件的文件流写入新创建的文件中
file.transferTo(newFile);
} catch (IOException e) {
e.printStackTrace();
}
return newFile;
}
/**
* 生成缩略图,并返回新生产图片的相对路径
* @param thumbnailInputStream
* @param targetAddr
* @return
*/
public static String generateThumbnail(InputStream thumbnailInputStream, String fileName, String targetAddr){
//获取文件随机名称
String realFileName = getRandomFileName();
//获取文件扩展名(后缀名)
String extension = getFileExtension(fileName);
//创建目标目录
makeDirsPath(targetAddr);
//拼接文件相对路径
String relativeAddr = targetAddr + realFileName + extension;
//新生产的文件的绝对路径
File dest = new File(PathUtil.getImgBasePath()+relativeAddr);
try {
Thumbnails.of(thumbnailInputStream)
.size(200,200)
.watermark(Positions.BOTTOM_RIGHT,ImageIO.read(new File(basePath + "/watermark.jpg")),0.5f)
.outputQuality(0.8f)
.toFile(dest);
} catch (IOException e) {
e.printStackTrace();
}
return relativeAddr;
}
/**
* 创建目标路径所涉及到的目录, 如 D:/tmp/one/two/xxx.jpg , 那么/tmp/one/two这三个文件夹都得自动创建
* @param targetAddress
*/
private static void makeDirsPath(String targetAddress) {
//获取文件全路径 ~ ~ 全路径 = 根路径 + 相对路径
String fileParentPath = PathUtil.getImgBasePath() + targetAddress;
//获取文件全路径目录
File dirPath = new File(fileParentPath);
//判断目录是否存在,不存在就创建该目录
if(!dirPath.exists()){
dirPath.mkdirs();
}
}
/**
* 获取文件扩展名
* @param filename
* @return
*/
private static String getFileExtension(String filename) {
//获取原始文件扩展名
String fileExtension = filename.substring(filename.lastIndexOf("."));
return fileExtension;
}
/**
* 生产随机文件名 ~ ~ 当前的(年月日时分秒 +5位随机数)
* @return
*/
public static String getRandomFileName() {
//获取10000~99999之间的5位随机数
int randomNumber = random.nextInt(99999) + 10000;
//获取当前时间,并按指定时间格式返回
String nowTime = format.format(new Date());
String randomFileName = nowTime + randomNumber;
return randomFileName;
}
}--
@Service("shopService")
public class ShopServiceImpl implements ShopService {
@Autowired
private ShopDao shopDao;
@Transactional(propagation = Propagation.REQUIRED)
public ShopExecution addShop(Shop shop, InputStream shopImgInputStream, String fileName) {
if(shop==null){
return new ShopExecution(ShopStateEnum.NULL_SHOP);
}
try {
//给店铺信息赋初始值
shop.setPriority(0);
shop.setAdvice("审核中");
shop.setEnableStatus(ShopStateEnum.CHECK.getState());
shop.setCreateTime(new Date());
shop.setLastEditTime(new Date());
//1、添加店铺信息
int effectNum = shopDao.insertShop(shop);
if(effectNum<=0){
//抛出RunTimeException异常(或继承了RunTimeException的子类异常),事务会进行回滚,
//(如果是抛出Exception异常,事务不会进行回滚)
throw new RuntimeException("店铺创建失败!");
}else{
if(shopImgInputStream != null){
//2、存储图片
try{
addShopImg(shop, shopImgInputStream,fileName);
}catch (Exception e){
throw new RuntimeException("addShopImg error: " + e.getMessage());
}
//3、更新店铺的图片地址
effectNum = shopDao.updateShop(shop);
if(effectNum<=0){
//抛出RunTimeException异常(或继承了RunTimeException的子类异常),事务会进行回滚,
//(如果是抛出Exception异常,事务不会进行回滚)
throw new RuntimeException("更新店铺的图片地址失败!");
}
}
}
}catch (Exception e){
throw new RuntimeException("addShop error: " + e.getMessage());
}
return new ShopExecution(ShopStateEnum.CHECK,shop);
}
private void addShopImg(Shop shop, InputStream shopImgInputStream, String fileName) {
//获取shop图片目录的相对路径
String dest = PathUtil.getShopImagePath(shop.getShopId());
//生成缩略图,并返回新生产图片的相对路径
String shopImgAddr = ImageUtil.generateThumbnail(shopImgInputStream,fileName,dest);
//设置shop图片地址
shop.setShopImg(shopImgAddr);
}
}--
@Controller
@RequestMapping("/shop_admin")
public class ShopManagementController {
@Autowired
private ShopService shopService;
@Autowired
private ShopCategoryService shopCategoryService;
@Autowired
private AreaService areaService;
/**
* 获取店铺分类和区域信息,(然后通过Ajax获取这些信息,进行页面的局部刷新)
* @return
*/
@RequestMapping("/get_shop_info")
@ResponseBody
private Map<String,Object> getShopInfo(){
Map<String,Object> map = new HashMap<String, Object>();
try{
List<ShopCategory> shopCategoryList = shopCategoryService.getShopCategoryList(new ShopCategory());
List<Area> areaList = areaService.getAreaList();
map.put("shopCategoryList",shopCategoryList);
map.put("areaList",areaList);
map.put("success",true);
}catch (Exception e){
map.put("success",false);
map.put("error:",e.getMessage());
}
return map;
}
/**
* 注册店铺
* @param request
* @return
*/
@RequestMapping("/register_shop")
@ResponseBody
private Map<String,Object> registerShop(HttpServletRequest request){
Map<String,Object> map = new HashMap<String, Object>();
if(!VerifyCodeUtil.checkVerifyCode(request)){
map.put("success",false);
map.put("errorMsg","验证码错误!");
return map;
}
//1、接收并转化相应的参数, 包括店铺信息和图片信息
String shopStr = HttpServletRequestUtil.getString(request,"shopStr");
ObjectMapper mapper = new ObjectMapper();
Shop shop = null;
try{
shop = mapper.readValue(shopStr,Shop.class);
}catch (Exception e){
map.put("success",false);
map.put("errorMsg",e.getMessage());
return map;
}
CommonsMultipartFile shopImg = null;
CommonsMultipartResolver commonsMultipartResolver =
new CommonsMultipartResolver(request.getSession().getServletContext());
if(commonsMultipartResolver.isMultipart(request)){
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
}else{
map.put("success",false);
map.put("errorMsg","上传图片不能为空!");
return map;
}
//2、注册店铺
if(shop != null && shopImg !=null){
Person person = new Person();
person.setUserId(1L);
shop.setOwner(person);
ShopExecution shopExecution = null;
try {
shopExecution = shopService.addShop(shop,shopImg.getInputStream(),shopImg.getOriginalFilename());
if(shopExecution.getState()== ShopStateEnum.CHECK.getState()){
map.put("success",true);
}else{
map.put("success",false);
map.put("errorMsg",shopExecution.getStateInfo());
}
} catch (IOException e) {
map.put("success",false);
map.put("errorMsg",e.getMessage());
}
return map;
}else{
map.put("success",false);
map.put("errorMsg","店铺信息不能为空!");
return map;
}
}
}--
$(function () {
var initUrl = '/o2o/shop_admin/get_shop_info';
var registerShopUrl = '/o2o/shop_admin/register_shop';
getShopInitInfo();
function getShopInitInfo() {
//$表示jquery对象,例如$.post(),$.get(),$.ajax()等这些都是jquery这个对象的方法
$.getJSON(initUrl,function (data) {
if(data.success){
var tempHtml = '';
var tempAreaHtml = '';
data.shopCategoryList.map(function(item,index) {
tempHtml += '<option data-id="' + item.shopCategoryId + '">'
+ item.shopCategoryName + '</option>';
});
data.areaList.map(function(item,index) {
tempAreaHtml += '<option data-id="' + item.areaId + '">'
+ item.areaName + '</option>';
});
$('#shop-category').html(tempHtml);
$('#area').html(tempAreaHtml);
}
});
$('#submit').click(function () {
var shop = {};
shop.shopName = $('#shop-name').val();
shop.shopAddress = $('#shop-address').val();
shop.shopPhone = $('#shop-phone').val();
shop.shopDesc = $('#shop-desc').val();
shop.shopCategory = {
shopCategoryId : $('#shop-category').find('option').not(function(){
return !this.selected;
}).data('id')
};
shop.area = {
areaId : $('#shop-category').find('option').not(function(){
return !this.selected;
}).data('id')
};
var shopImg = $('#shop-img')[0].files[0];
var verifyCode = $('#j_captcha').val();
var formData = new FormData();
if(!verifyCode){
$.toast('请输入验证码');
return;
}
formData.append('verifyCode',verifyCode);
formData.append('shopImg',shopImg);
formData.append('shopStr',JSON.stringify(shop));
$.ajax({
url: registerShopUrl,
type: 'POST',
data: formData,
contentType: false,
processData: false,
cache: false,
success: function(data){
if(data.success){
$.toast('提交成功!');
}else{
$.toast('提交失败!'+data.errMsg);
}
//进行提交后,不管成功还是失败,都对验证码进行更新
$('#captcha_img').click();
}
});
});
}
});--
public class VerifyCodeUtil {
public static boolean checkVerifyCode(HttpServletRequest request){
//获取生产的验证码
String verifyCodeGenerated = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
//获取实际提交的验证码
String verifyCodeActual = HttpServletRequestUtil.getString(request,"verifyCode");
//判断实际提交的验证码是否与生产的验证码是否一致
if(verifyCodeActual == null && !verifyCodeActual.equals(verifyCodeGenerated)){
return false;
}
return true;
}
}--
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <!-- 1、导入spring-service.xml配置文件 --> <import resource="classpath:spring/spring-service.xml"/> <!--2、自动扫描web包--> <context:component-scan base-package="com.cd.store.web"/> <!--3、开启spring mvc注解模式--> <mvc:annotation-driven/> <!--4、静态资源默认servlet配置: 1、加入对静态资源(js、css、jpg、png、git等. . .) 2、允许使用'/'做整体映射--> <!--即: resources目录下的静态资源不要用DispatcherServlet去拦截, 而是,交由默认servlet(<mvc:default-servlet-handler/>)来处理--> <mvc:resources mapping="/resources/**" location="/resources/"/> <!--默认servlet--> <mvc:default-servlet-handler/> <!--5、配置视图解析器--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!--视图前缀--> <property name="prefix" value="/WEB-INF/html/"/> <!--视图后缀--> <property name="suffix" value=".html"/> </bean> <!--文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"/> <!-- 上传文件的最大字节数 1024个字节为1kB, 1024kB为1M 1024*1024*10 = 10M , 上传文件的大小不能超过10M--> <property name="maxUploadSize" value="10485760"/> <!-- 最大内存也限制为10M --> <property name="maxInMemorySize" value="10485760"/> </bean> </beans>
--
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- 验证码相关属性的配置 --> <servlet> <servlet-name>Kaptcha</servlet-name> <servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class> <!-- 定义 Kaptcha 的样式 --> <!-- 是否有边框 --> <init-param> <param-name>kaptcha.border</param-name> <param-value>no</param-value> </init-param> <!-- 字体颜色 --> <init-param> <param-name>kaptcha.textproducer.font.color</param-name> <param-value>red</param-value> </init-param> <!-- 图片宽度 --> <init-param> <param-name>kaptcha.image.width</param-name> <param-value>135</param-value> </init-param> <!-- 图片高度 --> <init-param> <param-name>kaptcha.image.height</param-name> <param-value>50</param-value> </init-param> <!-- 使用哪些字符生成验证码 --> <init-param> <param-name>kaptcha.textproducer.char.string</param-name> <param-value>ACDEFHKPRSTWX3456975</param-value> </init-param> <!-- 字体大小 --> <init-param> <param-name>kaptcha.textproducer.font.size</param-name> <param-value>43</param-value> </init-param> <!-- 干扰线的颜色 --> <init-param> <param-name>kaptcha.noise.color</param-name> <param-value>black</param-value> </init-param> <!-- 字符个数 --> <init-param> <param-name>kaptcha.textproducer.char.length</param-name> <param-value>4</param-value> </init-param> <!-- 字体 --> <init-param> <param-name>kaptcha.textproducer.font.names</param-name> <param-value>Arial</param-value> <!--Arial是宋体字--> </init-param> </servlet> <servlet-mapping> <servlet-name>Kaptcha</servlet-name> <!-- 外部访问路径 --> <url-pattern>/Kaptcha</url-pattern> </servlet-mapping> <!--前置控制器 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--加载spring-web.xml配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/spring-web.xml</param-value> </init-param> </servlet> <!--配置servlet映射关系,将servlet与url绑定,通过别名匹配来绑定--> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <!--拦截所有路径型请求--> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
--
function changeVerifyCode(img) {
img.src = "../Kaptcha?" + Math.floor(Math.random() * 100);
}--
CREATE TABLE `area` (
`area_id` int(4) NOT NULL AUTO_INCREMENT COMMENT '区域id',
`area_name` varchar(100) NOT NULL COMMENT '区域名称',
`priority` int(3) NOT NULL DEFAULT '0' COMMENT '权重/优先级',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`last_edit_time` datetime DEFAULT NULL COMMENT '更新时间',
PRIMARY KEY (`area_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `area` VALUES ('1', '爱联', '1', '2019-10-02 23:33:32', '2019-10-10 16:40:10');
INSERT INTO `area` VALUES ('2', '荷坳', '2', '2019-10-03 02:34:08', '2019-10-10 16:40:14');--
CREATE TABLE `person` (
`user_id` int(10) NOT NULL AUTO_INCREMENT COMMENT '个人id',
`name` varchar(32) DEFAULT NULL COMMENT '姓名',
`profile_img` varchar(1024) DEFAULT NULL COMMENT '头像地址',
`email` varchar(1024) DEFAULT NULL COMMENT '邮箱',
`gender` varchar(2) DEFAULT NULL COMMENT '性别',
`enable_status` int(2) NOT NULL DEFAULT '0' COMMENT '0:禁止使用本商城,1:允许使用本商城',
`person_type` int(2) NOT NULL DEFAULT '1' COMMENT '1:顾客, 2:商家, 3:超级管理员',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`last_edit_time` datetime DEFAULT NULL COMMENT '最近更新时间',
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
INSERT INTO `person` VALUES ('1', '张三', 'test', 'test', '男', '0', '2', '2019-10-05 20:33:43', '2019-10-05 20:33:49');--
CREATE TABLE `shop_category` (
`shop_category_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '店铺类别id',
`shop_category_name` varchar(20) NOT NULL DEFAULT '' COMMENT '店铺类别名称',
`shop_category_desc` varchar(1000) DEFAULT '' COMMENT '店铺类别简介',
`shop_category_img` varchar(1000) DEFAULT NULL COMMENT '店铺类别图片',
`priority` int(2) NOT NULL DEFAULT '0' COMMENT '店铺类别权重',
`create_time` datetime DEFAULT NULL COMMENT '店铺类别创建时间',
`last_edit_time` datetime DEFAULT NULL COMMENT '店铺类别最近更新时间',
`parent_id` int(11) DEFAULT NULL COMMENT '店铺类别上级分类id',
PRIMARY KEY (`shop_category_id`),
KEY `fk_parentId` (`parent_id`),
CONSTRAINT `fk_parentId` FOREIGN KEY (`parent_id`) REFERENCES `shop_category` (`shop_category_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8;
INSERT INTO `shop_category` VALUES ('5', '美容美发', '一级分类', null, '1', '2019-10-09 02:05:58', '2019-10-09 02:06:01', null);
INSERT INTO `shop_category` VALUES ('6', '美食饮品', '一级分类', null, '1', '2019-10-09 02:06:32', '2019-10-09 02:06:48', null);
INSERT INTO `shop_category` VALUES ('7', '咖啡', '二级分类', null, '0', '2019-10-09 02:07:53', '2019-10-09 02:07:58', '6');
INSERT INTO `shop_category` VALUES ('8', '自助餐', '二级分类', null, '0', '2019-10-09 16:04:10', '2019-10-09 16:04:13', '6');--
CREATE TABLE `shop` (
`shop_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '店铺id',
`shop_name` varchar(20) DEFAULT NULL COMMENT '//店铺名称',
`shop_desc` varchar(1000) DEFAULT NULL COMMENT '店铺描述',
`shop_address` varchar(100) DEFAULT NULL COMMENT '店铺地址',
`shop_phone` varchar(20) DEFAULT NULL COMMENT '商家电话',
`shop_img` varchar(100) DEFAULT NULL COMMENT '店铺图片',
`priority` int(3) DEFAULT '0' COMMENT '权重',
`advice` varchar(1000) DEFAULT NULL COMMENT '超级管理员给商家的提醒',
`enable_status` int(2) DEFAULT '0' COMMENT '店铺状态 -1:不可用 0:审核 1:可用',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`last_edit_time` datetime DEFAULT NULL COMMENT '最近更新时间',
`owner_id` int(10) NOT NULL COMMENT '店铺创建人',
`shop_category_id` int(11) DEFAULT NULL COMMENT '店铺类别',
`area_id` int(4) DEFAULT NULL COMMENT '店铺所属区域',
PRIMARY KEY (`shop_id`),
KEY `fk_owner_id` (`owner_id`),
KEY `fk_area_id` (`area_id`),
KEY `fk_shop_category_id` (`shop_category_id`),
CONSTRAINT `fk_area_id` FOREIGN KEY (`area_id`) REFERENCES `area` (`area_id`),
CONSTRAINT `fk_owner_id` FOREIGN KEY (`owner_id`) REFERENCES `person` (`user_id`),
CONSTRAINT `fk_shop_category_id` FOREIGN KEY (`shop_category_id`) REFERENCES `shop_category` (`shop_category_id`)
) ENGINE=InnoDB AUTO_INCREMENT=23 DEFAULT CHARSET=utf8;
INSERT INTO `shop` VALUES ('18', '咖啡馆', 'test2', 'test2', 'test2', 'upload\\shop\\18\\2019101100133427562.jpg', '0', '审核通过', '1', '2019-10-11 00:13:34', '2019-10-11 00:13:34', '1', '7', '2');--
添加店铺的代码我已尽可能的贴出来了,麻烦老师仔细看一下,谢谢老师。
再找不到错误我就要奔溃了
36
收起
正在回答
2回答
同学你好,
报错的原因,的确是由于外键导致的,非常理解同学的心情,接下来慢慢的找一下原因,找错也是一种学习和成长~~
经过老师测试同学的代码,是可以正常插入的呢,看同学贴出来的数据库的数据,如果插入的area为2也是正确的。建议同学按以下思路排查一下。
数据插入之前,打断点查看一下shop.area.areaId是什么

查看一个数据库中area中是否存在id为这个值的数据。
如果我的回答解决了你的疑惑,请采纳,祝学习愉快~
4. SSM到Spring Boot入门与综合实战
- 参与学习 人
- 提交作业 323 份
- 解答问题 8263 个
本阶段将带你学习主流框架SSM,以及SpringBoot ,打通成为Java工程师的最后一公里!
了解课程

恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星