实体
IdCard.java
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@Table("t_person_id_card")
public class IdCard extends BasePureEntity {
private String idNum;
private String address;
/**
* 一对一
* oneToOne = true
*/
@OneToMany(subTable = "t_person", joinValue = "id_card_id", cascadeSaveOrUpdate = true, oneToOne = true, reversePropertyName = "idCard")
private Person person;
}
Person.java
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@Table("t_person")
public class Person extends BasePureEntity {
private String name;
@ManyToOne(parentTable = "t_person_id_card", value = "id_card_id", cascadeSaveOrUpdate = true)
private IdCard idCard;
}
运行 TableGenerator
生成SQL,参考sharp-database中的TableGenerator根据实体对象生成表
生成的SQL
create table t_person_id_card
(
id bigint not null comment '主键'
primary key,
id_num varchar(32) null,
address varchar(32) null,
created_by bigint null,
created_at datetime null,
updated_by bigint null,
updated_at datetime null,
is_deleted bit null
);
create table t_person
(
id bigint not null comment '主键'
primary key,
name varchar(32) null,
id_card_id bigint null,
created_by bigint null,
created_at datetime null,
updated_by bigint null,
updated_at datetime null,
is_deleted bit null
);
生成DAO
IdCardDAO
@Repository
public class IdCardDAO extends BaseDAOImpl<IdCard> {
}
PersonDAO
@Repository
public class PersonDAO extends BaseDAOImpl<Person> {
}
测试
@SpringBootTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class PersonTest {
@Autowired
private PersonDAO personDAO;
@Autowired
private IdCardDAO idCardDAO;
@Test
@Order(0)
public void savePerson() {
Person person = Person.builder()
.name("Rick")
.idCard(IdCard.builder().idNum("32128787988762").address("江苏").build())
.build();
personDAO.insert(person);
}
@Test
@Order(0)
public void saveCardId() {
Person person = Person.builder()
.name("Rick")
.build();
IdCard idCard = IdCard.builder().idNum("32128787988762").address("陕西")
.person(person)
.build();
idCardDAO.insert(idCard);
}
@Order(1)
@Test
public void findPersonById() {
Person person = personDAO.selectById(552098712424472576L).get();
assertThat(person.getName()).isEqualTo("Rick");
assertThat(person.getIdCard().getIdNum()).isEqualTo("32128787988762");
}
@Order(2)
@Test
public void findIdCardById() {
final IdCard idCard = idCardDAO.selectById(552098712365752320L).get();
assertThat(idCard.getPerson().getName()).isEqualTo("Rick");
assertThat(idCard.getIdNum()).isEqualTo("32128787988762");
}
}