0

我想在 Person 和 Address 之间建立 oneToOne 关系。所以我的实体将是(没有getter和setter):

public class Address {
    private Integer addressId;
    private String streetAddress;
    ...getter and setter
}

public class Person {
    private Integer personId;
    private String name;
    private Integer addressId;
    ...getter and setter
}

我有一个人的映射器和一个地址的映射器:

@Mapper
public interface AddressMapper {

    @Insert("Insert into address (streetAddress) values(#{streetAddress})")
    @Options(useGeneratedKeys = true, flushCache = FlushCachePolicy.TRUE, keyProperty="addressId")
    public Address saveAddress(Address address);

    @Select("SELECT * FROM Address")
    public List<Address> getAll();
}

@Mapper
public interface PersonMapper {

    @Insert("Insert into person(name,addressId) values (#{name},#{addressId})")
    public Integer save(Person person);

    @Select("select * from Person ")
    @MapKey("personId")
    Map<Integer, Person> getAllPerson();

}

然后我使用一个控制器来生成一个人并关联一个地址(这只是一个简单的例子):

@GetMapping("/insert")
public Integer insertPerson() {
    Person person = new Person("Nome1");
    Address address = new Address("via test");
    int addressId = addressMapper.saveAddress(address);
    person.setAddressId(addressId);
    return personMapper.save(person);
}

我的问题是 addressMapper.saveAddress(address); 返回保存的地址数而不是 id。有没有办法让它返回使用 Java 配置插入的地址的 ID?

否则可以以这种方式使用 Person 实体吗?

public class Person {
    private Integer personId;
    private String name;
    private Address addressId;
    ...getter and setter
}

Github 代码(它是公开的,因此您可以根据需要克隆存储库):

https://github.com/Mazzotta13/MyBatisExample

4

0 回答 0