外键约束无法添加或更新数据库"无法添加或更新子行:外键约束失败"

时间:2016-11-30 07:44:52

标签: java spring model-view-controller

我正在尝试保存一条评论,其中我使用来自客户表的外键(c_id),但它说

"Cannot add or update a child row: a foreign key constraint fails 
(`db_hotel`.`tbl_comments`, CONSTRAINT `tbl_comments_ibfk_1` FOREIGN KEY (`c_id`)"

我的实体类

public class Comments {
    private int commentsId;
    private Customer customer;
    private String message;

    public Comments() {
    }

    public Comments(int commentsId, Customer customer, String message) {
        this.commentsId = commentsId;
        this.customer = customer;
        this.message = message;
    }

    public int getCommentsId() {
        return commentsId;
    }

    public void setCommentsId(int commentsId) {
        this.commentsId = commentsId;
    }

    public Customer getCustomer() {
        return customer;
    }

    public void setCustomer(Customer customer) {
        this.customer = customer;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    @Override
    public String toString() {
        return "Comments{" + "commentsId=" + commentsId + ", customer=" + customer + ", message=" + message + '}';
    }


}

我的CRUD操作实现部分

@Repository(value = "CommentsDAO")
public class CommentsDAOImpl implements CommentsDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<Comments> getALL() throws SQLException {
        return jdbcTemplate.query(SQLConstant.COMMENTS_GETALL, new RowMapper<Comments>() {

            @Override
            public Comments mapRow(ResultSet rs, int i) throws SQLException {
                return mapData(rs);
            }
        });
    }

    @Override
    public int insert(Comments comm) throws SQLException {
        return jdbcTemplate.update(SQLConstant.COMMENTS_INSERT, new Object[]{comm.getCommentsId(), comm.getCustomer().getC_id(), comm.getMessage()});
    }

    private Comments mapData(ResultSet rs) throws SQLException {
        Comments comments = new Comments();
        comments.setCommentsId(rs.getInt("comments_id"));
        Customer customer = new Customer();
        customer.setC_id(rs.getInt("c_id"));
        customer.setFirstName(rs.getString("first_name"));
        customer.setLastName(rs.getString("last_name"));
        customer.setEmail(rs.getString("email"));
        customer.setContactNo(rs.getInt("contact_no"));
        comments.setCustomer(customer);
        comments.setMessage(rs.getString("message"));
        return comments;
    }

    @Override
    public int update(Comments comm) throws SQLException {
        return jdbcTemplate.update(SQLConstant.COMMENTS_UPDATE, new Object[]{comm.getMessage(), comm.getCustomer().getC_id(), comm.getCommentsId()});
    }

    @Override
    public int delete(int commentsId) throws SQLException {
        return jdbcTemplate.update(SQLConstant.CUSTOMER_DELETE, new Object[]{commentsId});
    }

    @Override
    public Comments getById(int commentsId) throws SQLException {
        return (Comments) jdbcTemplate.query(SQLConstant.COMMENTS_GETBYID, new Object[]{commentsId}, new ResultSetExtractor<Comments>() {

            @Override
            public Comments extractData(ResultSet rs) throws SQLException, DataAccessException {
                Comments comments = null;
                if (rs.next()) {
                    comments = new Comments();
                    comments.setCommentsId(rs.getInt("comments_id"));
                    Customer customer = new Customer();
                    customer.setC_id(rs.getInt("c_id"));
                    customer.setFirstName(rs.getString("first_name"));
                    customer.setLastName(rs.getString("last_name"));
                    customer.setEmail(rs.getString("email"));
                    customer.setContactNo(rs.getInt("contact_no"));
                    comments.setCustomer(customer);
                    comments.setMessage(rs.getString("message"));

                }
                return comments;
            }
        });
    }

}

控制器部分

 @Controller
 @RequestMapping(value="/admin/comments")
 public class CommentsController {
     @Autowired
     private CommentsService commentsService;
     @Autowired
     private CustomerService customerService;


     @RequestMapping(method = RequestMethod.GET)
     public String index (ModelMap map) throws SQLException{
         map.addAttribute("Comments",commentsService.getALL());
         return "admin/comments/index";
     }
     @RequestMapping(value="/add",method=RequestMethod.GET)
     public ModelAndView add(HttpServletRequest request) throws SQLException {
         ModelAndView mv= new ModelAndView("/admin/comments/add");
         String  c_id=null;
         if (request.getParameter("c_id")!=null && !request.getParameter("c_id").equals("") ) {
                c_id=request.getParameter("c_id");
         } 

         mv.addObject("Customer", customerService.getALL());
         return mv;
     }

     @RequestMapping(value = "/delete/{commentsId}",method = RequestMethod.GET)
     public String delete(@PathVariable("commentsId") int commentsId)throws SQLException {
         commentsService.delete(commentsId);
         return  "redirect:/admin/comments";
     }

     @RequestMapping(value="/save",method=RequestMethod.POST)
     public String save(@ModelAttribute ("Comments")Comments comment, @ModelAttribute("Customer")Customer customer) throws SQLException {
         try {  
             comment.setCustomer(customer);
             if(comment.getCommentsId()==0) {
                 commentsService.insert(comment);
             } else { 
                 commentsService.update(comment);
             }
         } catch (SQLException ex) {

         }
         return "redirect:/admin/comments";
     }
 }

这是用于插入或添加的JSP

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<h1>Add Users</h1>
<form:form modelAttribute="Comments" action="${SITE_URL}/admin/comments/save" method="post" role="form">

<div class="form-group">
            <label for="c_id">CustomerId</label>

            <select path="c_id" class="form-control">
                <option value="0">Select Commentor</spring:option>
                <c:forEach var="customer" items="${Customer}">
                    <option value="${customer.getC_id()}">${customer.getFirstName()}
                    </option>
                </c:forEach>
            </select>
        </div>      


<div class="form-group">
       <label>Message</label>
        <form:input path ="message"  placeholder="Enter Message" required="required" class="form-control"/>
    </div>

    <form:hidden path="commentsId"/>
    <div class="form-group"> 
    <button type="submit" class="btn btn-success" >Save</button>
    </div>
</form:form>

我试图解决它,因为两天但是无法弄清楚..

1 个答案:

答案 0 :(得分:0)

请在对表格执行任何操作之前禁用外键检查。只需查询 SET FOREIGN_KEY_CHECKS = 0 这将禁用与任何其他表的外键匹配。然后再次测试。  完成表后,再次启用它查询 SET FOREIGN_KEY_CHECKS = 1