0

I want to have a relation oneToOne between Person and Address. So my Entities will be (without getter and 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
}

I have a mapper for Person and a mapper for Address:

@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();

}

Then I use a Controller to generete a Person and associate an Address (it is just a simple example):

@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);
}

My problem is that addressMapper.saveAddress(address); return the number of addresses saved not the id. There is a way to make it return the ID of the address inserted using Java Configuration?

Otherwise is it possibile to use a Person entity in this way?

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

Github code (it is public so you can clone the repository if you want):

https://github.com/Mazzotta13/MyBatisExample

AM13
  • 661
  • 1
  • 8
  • 18
  • 1
    The generated ID is set to the property specified in `keyProperty`. After invoking `saveAddress()`, you can get the generated ID by calling `address.getAddressId()`. Please see the [doc](https://mybatis.org/mybatis-3/sqlmap-xml.html#insert.2C_update_and_delete) for details. – ave Jun 02 '20 at 18:50
  • Check this my answer: https://stackoverflow.com/questions/15456033/returning-values-from-mybatis-insert-mapped-methods/58026018#58026018 – Sergey Nemchinov Jun 08 '20 at 06:21

0 Answers0