有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个名为post\u locations的表(post\u id、location\u id、location\u name、created\u ts、updated\u ts、created\u by、updated\u by),两列上都有复合主键post\u id、location\u id。我尝试在两个列上定义id属性,但未能成功

我没有找到有关此主题的任何文档,请帮助我解决此问题


共 (1) 个答案

  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,因此属性是名称属性PK++名称主键属性(id.postId和id.locationId)。另一方面,需要添加id=true