Mybatis學習總結三之簡化sql對映xml檔案中的引用及解決欄位名與實體類屬性名不相同的衝突
一、為實體類定義別名,簡化sql對映xml檔案中的引用
我們在sql對映xml檔案中的引用實體類時,需要寫上實體類的全類名(包名+類名),如下:parameterType="com.aiit.pojo.User"這裡寫的實體類User的全類名com.aiit.pojo.User,
<insert id="insertOne" parameterType="com.aiit.pojo.User" > INSERT INTO tbl_user(tbl_user.name,tbl_user.age,tbl_user.address,tbl_user.birth) VALUES(#{name},#{age},#{address},#{birth}) </insert>
每次都寫這麼一長串內容挺麻煩的,現在我們把它簡化一下,如:
<insert id="insertOne" parameterType="user" >
INSERT INTO tbl_user(tbl_user.name,tbl_user.age,tbl_user.address,tbl_user.birth)
VALUES(#{name},#{age},#{address},#{birth})
</insert>
parameterType="user"簡化成這樣,我們需要在主配置檔案mybatis.xml檔案中為實體類="com.aiit.pojo.User
在mybatis.xml檔案中<configuration></configuration>標籤中新增如下配置:
特別注意要放在<configuration></configuration>標籤中,<environments></environments>上面
<typeAliases> <typeAlias type="com.aiit.pojo.User" alias="user" /> </typeAliases>
這樣就可以為com.aiit.pojo.User類定義了一個別名為user,以後user就代表了com.aiit.pojo.User類,這樣sql對映xml檔案中的凡是需要引用com.aiit.pojo.User類的地方都可以使用user來代替,這就達到了一個簡化實體類引用的目的。
另一種方法: <package name="com.aiit.pojo.User"/>就表示為這個包下面的所有實體類設定別名。MyBatis預設的設定別名的方式就是去除類所在的包後的簡單的類名,比如com.aiit.pojo.User這個實體類的別名就會被設定成User。
<typeAliases>
<!--只有包名-->
<package name="com.aiit.pojo"/>
</typeAliases>
<!--只需寫類名-->
<insert id="insertOne" parameterType="User" >
INSERT INTO tbl_user(tbl_user.name,tbl_user.age,tbl_user.address,tbl_user.birth)
VALUES(#{name},#{age},#{address},#{birth})
</insert>
二、解決欄位名與實體類屬性名不相同的衝突
我們平時寫專案時經常會遇到資料庫表中的欄位名和表對應實體類的屬性名稱不一定完全相同。下面我們來演示怎麼解決這個問題。
解決方法:我們在寫資料庫操作語言時,給表中的欄位名起個別名和實體類的屬性名一致就行了
1.定義實體類
package com.aiit.pojo;
import java.util.Date;
public class User {
private int id; //資料庫對應的欄位名user_id
private String name; //資料庫對應的欄位名user_name
private int age; //資料庫對應的欄位名user_age
private String address; //資料庫對應的欄位名address
private Date birth; //資料庫對應的欄位名birth
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public User(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public User() {
super();
}
public User(int id, String name, int age, String address, Date birth) {
super();
this.id = id;
this.name = name;
this.age = age;
this.address = address;
this.birth = birth;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + ", birth=" + birth + "]";
}
}
2.實體對映檔案配置UserMapper.xml
我們將查詢的欄位名都起一個和實體類屬性名相同的別名,這樣實體類的屬性名和查詢結果中的欄位名就可以一一對應上
<select id="selectOne" parameterType="int" resultType="com.aiit.pojo.User">
SELECT user_id id,user_name id,user_age age FROM tbl_user WHERE id=#{id}
</select>