首页 > mybatis 中多对一的情况下 如何插入数据

mybatis 中多对一的情况下 如何插入数据

public class Article {
    private int id;
    private Category category;
    private String title;
    private String content;
    private String uri;
    private Date date;

   // get set ....
}

model 这样定义的,表字段如下:

CREATE TABLE `article` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `c_id` int(11) DEFAULT NULL,
  `title` varchar(255) DEFAULT NULL,
  `content` text,
  `uri` varchar(255) DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `c_id` (`c_id`),
  CONSTRAINT `article_ibfk_1` FOREIGN KEY (`c_id`) REFERENCES `category` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8;

mapper中该如何配置insert ?


试试这样,确认 Category 中有id属性

<insert id="insertArticle">
  insert into article(id,c_id)
  values (#{id},#{category.id})
</insert>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN"
"http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
<mapper namespace="数据库操作dao">

    <insert id="insertId" parameterType="对象路径">
    insert into material_app(id,c_id,title,content,uri,date) values(
        #{id,jdbcType=VARCHAR},
        #{c_id,jdbcType=VARCHAR},
        #{title,jdbcType=VARCHAR},
        #{content,jdbcType=VARCHAR},
        #{uri,jdbcType=VARCHAR},
        #{date,jdbcType=VARCHAR}
        )
</insert>

</mapper>

【热门文章】
【热门文章】