在我的Spring Boot项目中,我正在使用MyBatis。我想知道如何使用一对一映射以及如何为映射类创建POJO。这是我使用过的SQL转储:
CREATE TABLE IF NOT EXISTS LANG(
ID BIGINT(10) NOT NULL AUTO_INCREMENT,
CODE VARCHAR(3) UNIQUE,
NAME VARCHAR(150),
PRIMARY KEY (ID)
);
CREATE TABLE IF NOT EXISTS PROVINCE(
ID BIGINT(10) NOT NULL AUTO_INCREMENT,
CODE VARCHAR(10) UNIQUE,
NAME VARCHAR(200),
LANG_CODE VARCHAR(3),
PRIMARY KEY (ID),
FOREIGN KEY(LANG_CODE) REFERENCES LANG(CODE)
);
和POJO是,
Language.java
public class Language {
private long id;
private String code;
private String name;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
省
public class Province {
private long id;
private String code;
private String name;
private String lang_code;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLang_code() {
return lang_code;
}
public void setLang_code(String lang_code) {
this.lang_code = lang_code;
}
}
答案 0 :(得分:2)
你应该改变你的实体省包括语言属性而不是重复它,它将是下一个:
public class Province {
private long id;
private Language language;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Language getLanguage() {
return language;
}
public void setLanguage(Language language) {
this.language = language;
}
}
另一方面,您需要使用语言选择操作创建Mapper,然后选择要绑定的省份。您可以使用注释查看下一个示例:
public interface MapperProvince {
@Select("select * from PROVINCE")
@Results({
@Result(id=true, property = "id", column = "ID"),
@Result(property="language", column="LANG_CODE",
one=@One(select="com.example.MapperProvince.findByCode"))
})
public List<Province> findAll();
@Select("select * from PROVINCE where ID = {id}")
@Results({
@Result(id=true, property = "id", column = "ID"),
@Result(property="language", column="LANG_CODE",
one=@One(select="com.example.MapperProvince.findByCode"))
})
public Province findById(long id);
@Select("select * from LANGUAGE where CODE = {code}")
@Results({
@Result(id=true, property = "id", column = "id"),
@Result(property = "code", column = "code"),
@Result(property = "name", column = "name")
})
public Language findByCode(String code);
}
如您所见,有一个语言操作按代码搜索,它在Table Province中链接。另一方面,当您搜索省时,您的语言属性的结果应该调用语言findByCode操作链接两者。我举了一个例子,搜索所有省份或只是通过ID。
答案 1 :(得分:0)
使用mybatis-spring-boot-starter(https://github.com/mybatis/spring-boot-starter)
进行设置LanguageMapper.java
@Mapper
public class LanguageMapper{
List<Language> queryLang();
}
LanguageMapper.xml
<select id="queryLang" resultType="Language">
select id,
code,
name
from LANG
</select>