简体   繁体   English

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

[英]how to define composite primary key in mybatis mapping

I have a table called post_locations(post_id,location_id,location_name,created_ts,updated_ts,created_by,updated_by) with composite primary key on two columns post_id,location_id . 我有一个名为post_locations(post_id,location_id,location_name,created_ts,updated_ts,created_by,updated_by)的在两列post_id,location_id上有复合主键。 I tried defining id property on both the column but couldn't succeed. 我尝试在两列上都定义id属性,但无法成功。

i did not find any documentation on this topic please help me solving this issue 我没有找到有关此主题的任何文档,请帮助我解决此问题

Searching for this problem, I come across this: http://mybatis-user.963551.n3.nabble.com/Composite-Keys-in-Resultmaps-td2775742.html 在搜索此问题时,我遇到了以下问题: http : //mybatis-user.963551.n3.nabble.com/Composite-Keys-in-Resultmaps-td2775742.html

I hope this can help, if not try give more details. 我希望这可以帮助您,如果不能尝试提供更多详细信息。

It is not difficult. 这并不困难。 If you have a entity like this: 如果您有这样的实体:

public class PostLocations {

    private PostLocationsPK id;

    //other properties...

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

Primary Key composite: 主键组合:

public class PostLocationsPK {

    private int postId, locationId;

    //getters, setters, constructors && equals
}

Your mapper should be like this: 您的映射器应如下所示:

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();

}

Property PostLocationsPK is id and properties in PostLocationsPK are postID and locationID, so the properties are name property PK + . 属性PostLocationsPK是id,而PostLocationsPK中的属性是postID和locationID,因此这些属性是名称属性PK + + name PK properties (id.postId and id.locationId). + 名称PK属性 (id.postId和id.locationId)。 On other hand, it is needed to add id=true. 另一方面,需要添加id = true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM