Mybatis的resultMap
Posted 陈彦斌
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis的resultMap相关的知识,希望对你有一定的参考价值。
Mybatis的SQL语句返回结果有两种
- resultType
- 查询出的字段在相应的POJO中必须有和它相同的字段对应,或者基本数据类型
- 适合简单查询
- resultMap
- 需要自定义字段,或者多表查询,一对多等关系,比resultType更强大
- 适合复杂查询
项目结构
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>net.cyb</groupId> <artifactId>cyb-mybatis</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.4</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.20</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.30</version> </dependency> </dependencies> </project>
mybatis-config.xml
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <!-- 引入外部配置文件 --> <properties resource="config/db.properties"></properties> <!--下划线自动映射驼峰字段--> <settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings> <!-- 数据库链接相关 --> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${db.driver}" /> <property name="url" value="${db.url}" /> <property name="username" value="${db.username}" /> <property name="password" value="${db.password}" /> </dataSource> </environment> </environments> <mappers> <!-- 添加映射文件 --> <mapper resource="mapper/VideoMapper.xml" /> </mappers> </configuration>
db.properties
db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://127.0.0.1:3306/cybclass
db.username=root
db.password=root
log4j.properties
#dev env [debug] product env [info]
log4j.rootLogger=ERROR, stdout
# Console output...
# 细化到打印某个mapper
# log4j.logger.包名.方法名=TRACE
log4j.logger.net.cybclass.online=TRACE
#log4j.logger.net.cybclass.online.dao.VideoMapper.selectById=TRACE
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
VideoMapper.xml
<?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"> <!-- namespace:名称空间,一般需要保持全局唯一,最好是和dao层的java接口一致。可以映射sql语句到对应的方法名称和参数、返回类型 --> <mapper namespace="net.cybclass.online.dao.VideoMapper"> <resultMap id="videoResultMap" type="net.cybclass.online.domain.Video"> <id column="id" property="id" jdbcType="INTEGER"></id> <result column="title2" property="title" jdbcType="VARCHAR"></result> <result column="summary" property="summary" jdbcType="VARCHAR"></result> </resultMap> <sql id="base_video_field2">id,title title2,summary</sql> <select id="selectBaseFieldByIdWithResultMap" resultMap="videoResultMap"> select <include refid="base_video_field2"></include> from video where id=#{id} </select> </mapper>
VideoMapper.java
package net.cybclass.online.dao; import net.cybclass.online.domain.Video; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; import java.util.Map; public interface VideoMapper { Video selectBaseFieldByIdWithResultMap(int id); }
Video.java
package net.cybclass.online.domain; import java.util.Date; /** * 视频类 */ public class Video { //内码 private int id; //视频标题 private String title; //视频详情 private String summary; //视频封面 private String coverImg; //加个 private int price; private int c_id; //评分 private double point; //创建日期 private Date create_time; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSummary() { return summary; } public void setSummary(String summary) { this.summary = summary; } public String getCoverImg() { return coverImg; } public void setCoverImg(String coverImg) { this.coverImg = coverImg; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getC_id() { return c_id; } public void setC_id(int c_id) { this.c_id = c_id; } public double getPoint() { return point; } public void setPoint(double point) { this.point = point; } public Date getCreate_time() { return create_time; } public void setCreate_time(Date create_time) { this.create_time = create_time; } @Override public String toString() { return "Video{" + "id=" + id + ", title=\'" + title + \'\\\'\' + ", summary=\'" + summary + \'\\\'\' + ", coverImg=\'" + coverImg + \'\\\'\' + ", price=" + price + ", c_id=" + c_id + ", point=" + point + ", create_time=" + create_time + \'}\'; } }
SqlSessionDemo.java
package net.cybclass.online; import net.cybclass.online.dao.VideoMapper; import net.cybclass.online.domain.Video; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.InputStream; import java.util.*; public class SqlSessionDemo { public static void main(String[] args) throws IOException { String resouce="config/mybatis-config.xml"; InputStream resourceAsStream = Resources.getResourceAsStream(resouce); SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream); try(SqlSession session=build.openSession()){ VideoMapper mapper = session.getMapper(VideoMapper.class); Video video = mapper.selectBaseFieldByIdWithResultMap(52); System.out.println(video.toString()); }catch (Exception e){ e.printStackTrace(); } } }
以上是关于Mybatis的resultMap的主要内容,如果未能解决你的问题,请参考以下文章