java 和 mybatis - 误解一对多关系 - 只有注释

java and mybatis - misunderstanding one-to-many relation - only annotations

我有两个表:Person 和 Dog。你知道那个人可能有不止一只狗。
我的模型是:

public class {
  int personId;
  List <Dog> dogs;
  String name;
  String surname;
}
public class Dog{
   String name;
   int dogId;
}

当谈到数据库时,它非常相似:

PersonID(PK), Name (String), surname(String)   
dogId(PK), name(String), IdOwner(FK)   

你能帮我在mybatis中写select吗?我试图阅读有关 @one@many 的内容。

如果您使用 MyBatis,您有两个选项,如 reference documentation 中所述:

  • Nested Select: By executing another mapped SQL statement that returns the complex type desired.
  • Nested Results: By using nested result mappings to deal with repeating subsets of joined results.

在你的情况下,因为你想加载许多关联,你必须使用 嵌套 Select,因为你不能使用 fetch outer join(仅与提取的一行关联)

嵌套Select

在此选项中,您应该需要添加对 select 的引用,它通过外键关系(在您的情况下是人的外键)加载 daya,在您的情况下是dogs 在 `ResultMap.

所以你应该有一个加载 Person table:

的查询
<select id="findById" resultMap="personResult">
  SELECT * FROM PERSON WHERE NAME = #{name}
</select>

其方法:

Person findById(String name); 

然后是按人键关系加载狗的查询:

<select id="findDogsByPerson" resultType="Dog">
  SELECT * FROM DOG WHERE ID_PERSON = #{namePerson}
</select>

及其方法:

List<Dog> findDogsByPerson(String namePerson);

然后您必须在结果映射中添加 select 作为关联,通过外键 (findDogsByPerson) 引用 select。在你的情况下有很多关联,所以你应该使用 collection 标签而不是 association.

<resultMap id="personResult" type="Person">
  <!--Other properties maps -->
  <!-- ..... -->
  <collection property="dogs" column="id_person" javaType="Dog" select="selectDogByPerson"/>
  <!-- ..... -->
</resultMap>

备选注解

如果需要,可以使用 annotations 来完成。它几乎相同,但 ResultMapSelect 超出了方法。它将使用引用许多关系的注释 @Many

@Select("SELECT * FROM PERSON WHERE NAME = #{name}")
    @Results(value = {
          @Result(property="name", column="name"),
          @Result(property="surname", column="surname"),
          @Result(property="dogs", javaType=List.class, column="name",
                             many=@Many(select="findDogsByPerson"))})
Person findById(String name); 

@Select("SELECT * FROM DOG WHERE ID_PERSON = #{namePerson}")
@Results(value = {
          @Result(property="name", column="name"),
          @Result(property="dogId", column="dogId")})
List<Dog> findDogsByPerson(String namePerson);