很多时候我们有这样的需求,数据库的字段名与实体类的属性名不一致,这个时候我们需要怎么做呢?有两种解决方案,第一种:直接在查询的时候使用别名,将别名设置成与实体类的属性名一致。第二种:使用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);
} }

【作者简介】

秦怀,公众号【秦怀杂货店】作者,技术之路不在一时,山高水长,纵使缓慢,驰而不息。这个世界希望一切都很快,更快,但是我希望自己能走好每一步,写好每一篇文章,期待和你们一起交流。

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

Mybatis【10】-- Mybatis属性名和查询字段名不同怎么做?的更多相关文章

  1. mybatis-属性名和查询字段名不相同的解决方案

    1.使用别名 resultType可以将查询结果直接映射为实体bean对象的条件是,sql查询的字段名和实体bean的属性名一致,通过反射机制完成对象的创建. select tid id,tname ...

  2. MyBatis学习总结(4)——解决字段名与实体类属性名不相同的冲突

    一.准备演示需要使用的表和数据 CREATE TABLE orders( order_id INT PRIMARY KEY AUTO_INCREMENT, order_no VARCHAR(20), ...

  3. Mybatis系列(二):优化MyBatis配置文件中的配置和解决字段名与实体类属性名不相同的冲突

    原文链接:http://www.cnblogs.com/xdp-gacl/p/4264301.html     http://www.cnblogs.com/xdp-gacl/p/4264425.ht ...

  4. mybatis——解决属性名和数据库字段名不一致问题(注解方式)

    当我们使用注解开发时有时会遇到数据库字段名与实体类属性名不一致的问题.xml方式开发可以通过结果集映射的方式解决,那注解方式开发要怎么解决呢? 注解解决方式: @Results()注解 Results ...

  5. Mybatis——实体类属性名和数据库字段名不同时的解决方案

    数据库的字段: 对应的实体类: 方案一: 在XML映射文件中使用的resultMap,优点:可以被重复使用. <resultMap id="BaseResultMap" ty ...

  6. mybatis——解决属性名和数据库字段名不一致问题

    首先说一下,我的数据库名字叫mybatis,里边有一张user表,表中有三个字段,id.name.pwd:然后实体类中对应三个属性id.name.password(id和name跟数据库字段名一致,但 ...

  7. Mysql查询的一些操作(查表名,查字段名,查当月,查一周,查当天)

    查询数据库中所有表名 select table_name from information_schema.tables where table_schema='tools' and table_typ ...

  8. 【转】Oracle 查询库中所有表名、字段名、表名说明、字段名说明

    转自 :http://gis-conquer.blog.sohu.com/170243422.html 查询所有表名:select t.table_name from user_tables t; 查 ...

  9. Oracle 查询库中所有表名、字段名、表名说明、字段名说明(原创)

    查询所有表名:select t.table_name from user_tables t;查询所有字段名:select t.column_name from user_col_comments t; ...

  10. mysql 查询字段名所在的表

    select * from (select * from information_schema.COLUMNS where table_schema = '数据库名') temp where colu ...

随机推荐

  1. Excel中制作目录的3种方法,你了解几种?

    点赞再看,养成习惯:言之无文,行而不远. 微信搜索[亦心Excel]关注这个不一样的自媒体人. 本文 GitHub https://github.com/hugogoos/Excel 已收录,包含Ex ...

  2. 后缀数组,SA

    主要是 \(O(n\log n)\) 倍增求 SA. (为什么这么短) const int N = 1e6 + 9; int n; int sa[N], sa_tmp[N], rk[N], ork[N ...

  3. .net core8 使用JWT鉴权(附当前源码)

    说明 该文章是属于OverallAuth2.0系列文章,每周更新一篇该系列文章(从0到1完成系统开发). 该系统文章,我会尽量说的非常详细,做到不管新手.老手都能看懂. 说明:OverallAuth2 ...

  4. MyBatisPlus——DML编程控制——乐观锁

    乐观锁 业务并发现象带来的问题:秒杀最后一单 用于中小型项目(2000请求以下) 添加一个数据库字段,使每次请求修改数据时,这个字段就加一,当有多人同时请求时,这些人同时获取到的都是相同的该字段,但当 ...

  5. Kubernetes Deployment控制器(二十)

    前面我们学习了 ReplicaSet 控制器,了解到该控制器是用来维护集群中运行的 Pod 数量的,但是往往在实际操作的时候,我们反而不会去直接使用 RS,而是会使用更上层的控制器,比如我们今天要学习 ...

  6. USB总线-Linux内核USB3.0主机控制器驱动框架分析(十二)

    1.概述 如下图所示,Linux内核中USB主机体系结构由五部分组成,分别为Application Software.USB Class Driver.USB Core((USB Driver).US ...

  7. uprobe的使用浅析

    uprobe是linux内核提供的一种trace用户态函数的机制 可以在不对二进制重新编译的情况下进行trace特定函数 本文描述了uprobe的基本使用方法 使用方法 官方的指引是这样的, 详细的可 ...

  8. 利用 ACME 实现SSL证书自动化配置更新

    最近收到腾讯云的通知SSL证书要到期了,本想直接申请的发现现在申请的免费SSL证书有效期只有90天了,顺便了解了一下原因是包括Google在内的国际顶级科技公司一直都有在推进免费证书90天有效期的建议 ...

  9. slot原理

    vue提供组件插槽能力, 允许开发者在封装组件时,把不确定的部分定义为插槽 : 作用:再不确定的内容位置占位,在子组件内使用 slot 标签写占位的内容 : 插槽的分类 : 默认插槽: 具名插槽:使用 ...

  10. M.2移动硬盘打造Win To Go系统:高效分区存储文件全攻略

    前言 大家好,我是 Frpee内网穿透 开发者 xnkyn, 曾经的我一直在互联网上学习技术,这次我要在博客园这片净土上给中国互联网技术做贡献,这是我在博客园写的第一篇技术文章,后续我会分享更多的技术 ...