1. 程式人生 > 實用技巧 >Mybatis【10】-- Mybatis屬性名和查詢欄位名不同怎麼做?

Mybatis【10】-- Mybatis屬性名和查詢欄位名不同怎麼做?

很多時候我們有這樣的需求,資料庫的欄位名與實體類的屬性名不一致,這個時候我們需要怎麼做呢?有兩種解決方案,第一種:直接在查詢的時候使用別名,將別名設定成與實體類的屬性名一致。第二種:使用resultType,自己定義對映關係。
整個專案的目錄如下:


首先,我們需要搭建資料庫mysql環境(test.sql),id我們寫成了sid,name我們寫成了sname,age我們寫成了sage:

#建立資料庫
CREATE DATABASE `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
#建立資料表
CREATE TABLE `student` ( `sid` INT NOT NULL AUTO_INCREMENT , `sname` VARCHAR(20) NOT NULL ,
`sage` INT NOT NULL , `score` DOUBLE NOT NULL , PRIMARY KEY (`sid`)) ENGINE = MyISAM;

Student.class實體類:

public class Student {
	private Integer id;
	private String name;
	private int age;
	private double score;
	public Student(){

    }
	public Student(String name, int age, double score) {
		super();
		this.name = name;
		this.age = age;
		this.score = score;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer 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 double getScore() {
		return score;
	}
	public void setScore(double score) {
		this.score = score;
	}
	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age
				+ ", score=" + score + "]";
	}
	
}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.test</groupId>
    <artifactId>test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <!-- mysql驅動包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>
        <!-- junit測試包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <!-- 日誌檔案管理包 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.12</version>
        </dependency>
    </dependencies>
</project>

主配置檔案mybatis.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 配置資料庫檔案 -->
    <properties resource="jdbc_mysql.properties">

    </properties>
    <!-- 別名,對資料物件操作全名太長,需要使用別名 -->
    <typeAliases>
        <!--<typeAlias type="bean.Student" alias="Student"/>-->
        <!--直接使用類名即可,對於整個包的路徑配置(別名),簡單快捷 -->
        <package name="bean"/>
    </typeAliases>
    <!-- 配置執行環境 -->
    <!-- default 表示預設使用哪一個環境,可以配置多個,比如開發時的測試環境,上線後的正式環境等 -->
    <environments default="mysqlEM">
        <environment id="mysqlEM">
            <transactionManager type="JDBC">
            </transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.user}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 註冊對映檔案 -->
    <mappers>
        <mapper resource="mapper/mapper.xml"/>
    </mappers>
</configuration>

資料庫配置檔案(jdbc_mysql.properties):

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&serverTimezone=UTC
jdbc.user=root
jdbc.password=123456

日誌配置檔案 log4j.prperties:

log4j.prpp
log4j.rootLogger=DEBUG, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[service] %d - %c -%-4r [%t] %-5p %c %x - %m%n
log4j.logger.java.sql.Statement = debug
log4j.logger.java.sql.PreparedStatement = debug
log4j.logger.java.sql.ResultSet =debug

使用到的工具類(MyBatisUtils.java):

public class MyBatisUtils {
    static private SqlSessionFactory sqlSessionFactory;

    static public SqlSession getSqlSession() {
        InputStream is;
        try {
            is = Resources.getResourceAsStream("mybatis.xml");
            if (sqlSessionFactory == null) {
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            }
            return sqlSessionFactory.openSession();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

介面定義(IStudentDao.java):

public interface IStudentDao {
    // 返回所有學生的資訊List
    public List<Student> selectAllStudents();
    // 根據id查詢學生
    public Student selectStudentById(int id);
}

介面實現類(StudentDaoImpl.class):

public class StudentDaoImpl implements IStudentDao {
    private SqlSession sqlSession;
    public List<Student> selectAllStudents() {
        List<Student> students ;
        try {
            sqlSession = MyBatisUtils.getSqlSession();
            students = sqlSession.selectList("selectAllStudents");
            //查詢不用修改,所以不用提交事務
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        return students;
    }

    public Student selectStudentById(int id) {
        Student student=null;
        try {
            sqlSession=MyBatisUtils.getSqlSession();
            student=sqlSession.selectOne("selectStudentById",id);
            sqlSession.commit();
        } finally{
            if(sqlSession!=null){
                sqlSession.close();
            }
        }
        return student;
    }
}

最主要的mapper檔案:

可以直接使用別名:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="abc">
    <select id="selectAllStudents" resultType="Student">
        select sid as id,sname as name,sage as age,score from student
    </select>
    <select id="selectStudentById" resultType="Student">
		select sid as id,sname as name,sage as age,score from student where sid=${value}
	</select>
</mapper>

或者可以自己定義對映:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="abc">
    <resultMap id="StudentMapper" type="Student">
        <id column="sid" property="id"/>
        <result column="sname" property="name"/>
        <result column="sage" property="age"/>
    </resultMap>
    <select id="selectAllStudents" resultMap="StudentMapper">
        select sid as id,sname as name,sage as age,score from student
    </select>
    <select id="selectStudentById" resultMap="StudentMapper">
		select sid as id,sname as name,sage as age,score from student where sid=${value}
	</select>
</mapper>



需要注意的點:

  • 有一個id屬性,這個是在其他地方使用的時候的id
  • Type - 實體類,可以寫別名,要不就要寫帶全路徑的類名
  • id - 標籤是為了標記出作為 ID 的結果可以幫助提高整體效能
  • result – 注入到欄位或 JavaBean 屬性的普通結果
  • association – 一個複雜型別的關聯;許多結果將包裝成這種型別巢狀結果對映 – 關聯可以指定為一個 resultMap 元素,或者引用一個
  • collection – 一個複雜型別的集合
    巢狀結果對映 – 集合可以指定為一個 resultMap 元素,或者引用一個
  • discriminator – 使用結果值來決定使用哪個 resultMap
    case – 基於某些值的結果對映
    巢狀結果對映 – 一個 case 也是一個對映它本身的結果,因此可以包含很多相 同的元素,或者它可以參照一個外部的 resultMap。
    如果物件名與屬性名一致,我們可以不把它寫入

測試類MyTest.class:

public class MyTest {
	private IStudentDao dao;
	@Before
	public void Before(){
		dao=new StudentDaoImpl();
	}
    /*
     * 查詢列表
     *
     */
    @Test
    public void testselectList(){
        List<Student> students=dao.selectAllStudents();
        if(students.size()>0){
            for(Student student:students){
                System.out.println(student);
            }
        }
    }
    /*
     * 通過id來查詢student
     *
     */
    @Test
    public void testselectStudentById(){
        Student student=dao.selectStudentById(1);
        System.out.println(student);
    }

}

【作者簡介】
秦懷,公眾號【秦懷雜貨店】作者,技術之路不在一時,山高水長,縱使緩慢,馳而不息。這個世界希望一切都很快,更快,但是我希望自己能走好每一步,寫好每一篇文章,期待和你們一起交流。

此文章僅代表自己(本菜鳥)學習積累記錄,或者學習筆記,如有侵權,請聯絡作者核實刪除。人無完人,文章也一樣,文筆稚嫩,在下不才,勿噴,如果有錯誤之處,還望指出,感激不盡~