关于mybatis:Mybatis10-Mybatis属性名和查询字段名不同怎么做

11次阅读

共计 6840 个字符,预计需要花费 18 分钟才能阅读完成。

很多时候咱们有这样的需要,数据库的字段名与实体类的属性名不统一,这个时候咱们须要怎么做呢?有两种解决方案,第一种:间接在查问的时候应用别名,将别名设置成与实体类的属性名统一。第二种:应用 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>

须要留神的点:

  • <resultMap></resultMap> 有一个 id 属性,这个是在其余中央应用的时候的 id
  • Type – 实体类,能够写别名,要不就要写带全门路的类名
  • id – 标签是为了标记出作为 ID 的后果能够帮忙进步整体性能
  • result – 注入到字段或 JavaBean 属性的一般后果
  • association – 一个简单类型的关联; 许多后果将包装成这种类型嵌套后果映射 – 关联能够指定为一个 resultMap 元素,或者援用一个
  • collection – 一个简单类型的汇合

嵌套后果映射 – 汇合能够指定为一个 resultMap 元素,或者援用一个

  • discriminator – 应用后果值来决定应用哪个 resultMap

case – 基于某些值的后果映射
嵌套后果映射 – 一个 case 也是一个映射它自身的后果, 因而能够蕴含很多相 同的元素,或者它能够参照一个内部的 resultMap。
如果对象名与属性名统一,咱们能够不把它写入 <resultMap></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);
    }

}

【作者简介】
秦怀,公众号【秦怀杂货店】作者,技术之路不在一时,山高水长,纵使迟缓,驰而不息。这个世界心愿所有都很快,更快,然而我心愿本人能走好每一步,写好每一篇文章,期待和你们一起交换。

此文章仅代表本人(本菜鸟)学习积攒记录,或者学习笔记,如有侵权,请分割作者核实删除。人无完人,文章也一样,文笔稚嫩,在下不才,勿喷,如果有谬误之处,还望指出,感激不尽~

正文完
 0