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):