mybatis映射中如何定义复合主键

how to define composite primary key in mybatis mapping

我有一个 table 叫 post_locations(post_id,location_id,location_name,created_ts,updated_ts,created_by,updated_by) 两列上有复合主键 post_id,location_id .我尝试在两个列上定义 id 属性 但没有成功。

我没有找到关于这个主题的任何文档请帮我解决这个问题

不难。如果您有这样的实体:

public class PostLocations {

    private PostLocationsPK id;

    //other properties...

    //constructor, getters && setters....
}

复合主键:

public class PostLocationsPK {

    private int postId, locationId;

    //getters, setters, constructors && equals
}

你的映射器应该是这样的:

public interface MapperEntity {

    @Select("select * from post_locations")
    @Results({
        @Result(id=true, property = "id.postId", column = "post_id"),
        @Result(id=true, property = "id.locationId", column = "location_id"),
        //OTHER PROPERTIES...
      })
    public List<PostLocations> findAll();

}

属性PostLocationsPK是id,PostLocationsPK中的属性是postID和locationID,所以属性是name属性PK+ + 名称 PK 属性(id.postId 和 id.locationId)。另一方面,需要添加 id=true.