user31481 user31481 - 4 months ago 61
SQL Question

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. I tried defining id property on both the column but couldn't succeed.

i did not find any documentation on this topic please help me solving this issue

Answer

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 + . + name PK properties (id.postId and id.locationId). On other hand, it is needed to add id=true.