user31481 user31481 - 3 months ago 31
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


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")
        @Result(id=true, property = "id.postId", column = "post_id"),
        @Result(id=true, property = "id.locationId", column = "location_id"),
    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.