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

时间:2016-07-21 12:29:26

标签: java mysql database mybatis

我有一个名为 post_locations(post_id,location_id,location_name,created_ts,updated_ts,created_by,updated_by)的表,其中复合主键位于两列 post_id,location_id 上。我尝试在列上定义id属性但是不能成功。

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

2 个答案:

答案 0 :(得分:1)

正在搜索此问题,我遇到了这个问题:http://mybatis-user.963551.n3.nabble.com/Composite-Keys-in-Resultmaps-td2775742.html

我希望这可以提供帮助,如果没有尝试提供更多细节。

答案 1 :(得分:1)

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

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。

相关问题