mybatis练习题
1. Xml映射文件中,除了常见的select|insert|updae|delete标签之外,还有哪些标签?
还有很多其他的标签,<resultMap>、<parameterMap>、<sql>、<include>、<selectKey>,加上动态sql的9个标签,trim|where|set|foreach|if|choose|when|otherwise|bind等,其中<sql>为sql片段标签,通过<include>标签引入sql片段,<selectKey>为不支持自增的主键生成策略标签。
2. Mapper接口的工作原理是什么?
Mapper 接口的工作原理是JDK动态代理,Mybatis运行时会使用JDK动态代理为Mapper接口生成代理对象proxy,代理对象会拦截接口方法,转而执行MapperStatement所代表的sql,然后将sql执行结果返回。
3. Mapper接口中的方法能重载吗?
Mapper接口里的方法,是不能重载的,因为是使用 全限名+方法名 的保存和寻找策略。 Mapper 接口的工作原理 是JDK动态代理,Mybatis运行时会使用JDK动态代理为Mapper接口生成代理对象proxy,代理对象会拦截接口方法,转而执行MapperStatement所代表的sql,然后将sql执行结果返回。
4. Mybatis动态sql是做什么的?
动态sql是指在进行sql操作的时候,传入的参数对象或者参数值,根据匹配的条件,有可能需要动态的去判断是否为空,循环,拼接等情况;
动态Sql的标签大致有以下几种:
1、if 和 where 标签和include标签
if标签中可以判断传入的值是否符合某种规则,比如是否不为空;
where标签可以用来做动态拼接查询条件,当和if标签配合的时候,不用显示的声明类似where 1=1这种无用的条件,来达到匹配的时候and会多余的情况;
include可以把大量重复的代码整理起来,当使用的时候直接include即可,减少重复代码的编写
2、choose、when、otherwise 标签
类似于 Java 中的 switch、case、default。
只有一个条件生效,也就是只执行满足的条件 when,没有满足的条件就执行 otherwise,表示默认条件;
3、foreach 标签
foreach标签可以把传入的集合对象进行遍历,然后把每一项的内容作为参数传到sql语句中,里面涉及到 item(具体的每一个对象), index(序号), open(开始符), close(结束符), separator(分隔符)
4、map参数
< map> 标签需要结合MyBatis的参数注解 @Param()来使用,需要告诉Mybatis配置文件中的collection="map"里的map是一个参数
5、set标签
适用于更新中,当匹配某个条件后,才会对该字段进行更新操作
6、trim标签
是一个格式化标签,主要有4个参数:
prefix(前缀)
prefixOverrides(去掉第一个标记)
suffix(后缀)
suffixOverrides(去掉最后一个标记)
5. Mybatis是否支持延迟加载?
什么是延迟加载?
延迟加载的条件:resultMap可以实现高级映射(使用association、collection实现一对一及一对多映射),association、collection具备延迟加载功能。
延迟加载的好处: 先从单表查询、需要时再从关联表去关联查询,大大提高 数据库性能,因为查询单表要比关联查询多张表速度要快。
延迟加载的实例: 如果查询订单并且关联查询用户信息。如果先查询订单信息即可满足要求,当我们需要查询用户信息时再查询用户信息。把对用户信息的按需去查询就是延迟加载。
Mybatis仅支持association关联对象和collection关联集合对象的延迟加载,association指的就是一对一,collection指的就是一对多查询。在Mybatis配置文件中,可以配置是否启用延迟加载lazyLoadingEnabled=true|false。
它的原理是,使用CGLIB创建目标对象的代理对象,当调用目标方法时,进入拦截器方法,比如调用a.getB().getName(),拦截器invoke()方法发现a.getB()是null值,那么就会单独发送事先保存好的查询关联B对象的sql,把B查询上来,然后调用a.setB(b),于是a的对象b属性就有值了,接着完成a.getB().getName()方法的调用。这就是延迟加载的基本原理。
当然了,不光是Mybatis,几乎所有的包括Hibernate,支持延迟加载的原理都是一样的。
6. Mybatis的Xml映射文件中,不同的Xml映射文件,id是否可以重复?
不同的Xml映射文件,如果配置了namespace,那么id可以重复;如果没有配置namespace,那么id不能重复.
(不管是什么id,即使不是同种类型,譬如说查询的id跟更新的id不一样也不行.反正就是所有id都不能重复,因为id就是一个标识)
7. 简述动态sql的执行原理?
>第一部分:在启动加载解析xml配置文件的时候进行解析,根据关键标签封装成对应的handler处理对象,封装成sqlSource对象存在mappedStatement。
调用流程:
I、SqlSessionFactoryBuilder对builder对象的时候,调用XMLConfigBuilder解析sqlMapConfig.xml配置文件,在解析过程中使用到了私有的mapperElement(XNode parent)方法
II、上面方法中通过构建XMLMapperBuilder,获取到所有的配置mapper配置,
在调用private void configurationElement(XNode context)方法进行解析mapper.xml,通过void buildStatementFromContext(List<XNode> list, String requiredDatabaseId)方法解析mapper.xml内的每一个标签
III、循环中构建XMLStatementBuilder对象,调用parseStatementNode()方法来封装mappedStatment对象,
IIII、在过程中需要构建sqlSource对象,通过XMLLanguageDriver对象进行处理,在XMLLanguageDriver中构建解析动态标签对象XMLScriptBuilder
第二部分:在执行过程中获取sqlSource中获取bondSql对象时,执行相应的标签handler
调用查询执行到BaseExecutor的query方法时候会去getBoundSql并且将参数传进去,
在sqlSource接口DynamicSqlSource实现类中,调用getBoundSql方法执行过程共创建DynamicContext对象进行判定解析封装成SqlSource对象返回。
- 编程题:
建表语句
SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `goods`;
CREATE TABLE `goods` (
`goodsId` int(11) NOT NULL AUTO_INCREMENT,
`goodsName` varchar(30) NOT NULL,
`goodsExplain` varchar(60) DEFAULT NULL,
`goodsPrice` int(11) NOT NULL,
`gtId` int(11) NOT NULL,
PRIMARY KEY (`goodsId`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS `goodstype`;
CREATE TABLE `goodstype` (
`gtId` int(11) NOT NULL AUTO_INCREMENT,
`gtName` varchar(30) NOT NULL,
`gtExplain` varchar(60) DEFAULT NULL,
PRIMARY KEY (`gtId`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `goods` VALUES ('1', '小米11 Ultra', '+199元得价值499元80W无线充套装', '5499', '1');
INSERT INTO `goods` VALUES ('2', '小米11 青春版', '全版本直降200元', '2099', '1');
INSERT INTO `goods` VALUES ('3', '小米10', '买赠129元冰封散热背夹', '3399', '1');
INSERT INTO `goods` VALUES ('4', 'Redmi Note 10 Pro', '付款前1000名赠价值99元小米定制T恤', '1699', '2');
INSERT INTO `goods` VALUES ('5', 'Redmi K40 Pro', '高考生认证立减100元', '2799', '2');
INSERT INTO `goods` VALUES ('6', 'Redmi 9', '购机赠小米移动流量卡', '799', '2');
INSERT INTO `goods` VALUES ('7', 'Redmi K40 游戏增强版', '购机前1000名赠小米定制T恤', '1999', '3');
INSERT INTO `goodstype` VALUES ('1', '小米手机', '小米手机类型的商品');
INSERT INTO `goodstype` VALUES ('2', 'Redmi手机', 'Redmi手机类型的商品');
INSERT INTO `goodstype` VALUES ('3', '游戏手机', '游戏手机类型的商品');
image.png
实体类
Goods
package com.neusoft.po;
public class Goods {
private Integer goodsId;
private String goodsName;
private String goodsExplain;
private Integer goodsPrice;
private Integer gtId;
private GoodsType goodsType;
public Integer getGoodsId() {
return goodsId;
}
public void setGoodsId(Integer goodsId) {
this.goodsId = goodsId;
}
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public String getGoodsExplain() {
return goodsExplain;
}
public void setGoodsExplain(String goodsExplain) {
this.goodsExplain = goodsExplain;
}
public Integer getGoodsPrice() {
return goodsPrice;
}
public void setGoodsPrice(Integer goodsPrice) {
this.goodsPrice = goodsPrice;
}
public Integer getGtId() {
return gtId;
}
public void setGtId(Integer gtId) {
this.gtId = gtId;
}
public GoodsType getGoodsType() {
return goodsType;
}
public void setGoodsType(GoodsType goodsType) {
this.goodsType = goodsType;
}
public Goods(Integer goodsId, String goodsName, String goodsExplain, Integer goodsPrice, Integer gtId,
GoodsType goodsType) {
super();
this.goodsId = goodsId;
this.goodsName = goodsName;
this.goodsExplain = goodsExplain;
this.goodsPrice = goodsPrice;
this.gtId = gtId;
this.goodsType = goodsType;
}
public Goods() {
super();
}
@Override
public String toString() {
return "Goods [goodsId=" + goodsId + ", goodsName=" +
goodsName + ", goodsExplain=" + goodsExplain + ", goodsPrice=" +
goodsPrice + ", gtId=" + gtId + ", goodsType=" + goodsType + "]";
}
}
GoodsType
package com.neusoft.po;
import java.util.List;
public class GoodsType {
private Integer gtId;
private String gtName;
private String gtExplain;
private List<Goods> goods;
public GoodsType(Integer gtId, String gtName, String gtExplain, List<Goods> goods) {
super();
this.gtId = gtId;
this.gtName = gtName;
this.gtExplain = gtExplain;
this.goods = goods;
}
public Integer getGtId() {
return gtId;
}
public void setGtId(Integer gtId) {
this.gtId = gtId;
}
public String getGtName() {
return gtName;
}
public void setGtName(String gtName) {
this.gtName = gtName;
}
public String getGtExplain() {
return gtExplain;
}
public void setGtExplain(String gtExplain) {
this.gtExplain = gtExplain;
}
public List<Goods> getGoods() {
return goods;
}
public void setGoods(List<Goods> goods) {
this.goods = goods;
}
@Override
public String toString() {
return "GoodsType [gtId=" + gtId + ", gtName=" + gtName + ", gtExplain=" + gtExplain + ", goods=" + goods + "]";
}
public GoodsType() {
super();
}
}
DBUtil
package com.neusoft.util;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class DBUtil {
public static SqlSessionFactory sqlSessionFactory = null;
public static SqlSessionFactory getSqlSessionFactory() {
if(sqlSessionFactory==null){
String resource = "SqlMapConfig.xml";
try {
Reader reader = Resources.getResourceAsReader(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
} catch (IOException e) {
e.printStackTrace();
}
}
return sqlSessionFactory;
}
}
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/good?characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
SqlMapConfig.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="db.properties"></properties>
<!-- 定义类别名 -->
<typeAliases>
<package name="com.neusoft.po"/>
</typeAliases>
<!-- 配置数据源相关属性和事务 -->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<!-- 加载映射文件 -->
<mappers>
<package name="com.neusoft.mapper"/>
</mappers>
</configuration>
1、按照id查找商品
测试类
package com.neusoft.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.neusoft.mapper.GoodsMapper;
import com.neusoft.mapper.GoodsTypeMapper;
import com.neusoft.po.Goods;
import com.neusoft.po.GoodsType;
import com.neusoft.util.DBUtil;
public class Test {
public static void main(String[] args) {
SqlSession sqlSession = DBUtil.getSqlSessionFactory().openSession();
GoodsMapper mapper = sqlSession.getMapper(GoodsMapper.class);
System.out.println("=============== 按照id查找商品 ====================");
Goods goods = mapper.getGoodsById(1);
System.out.println(goods);
}
}
GoodsMapper接口
package com.neusoft.mapper;
import java.util.List;
import com.neusoft.po.Goods;
public interface GoodsMapper {
//按照id查找商品
public Goods getGoodsById(Integer goodsId);
}
GoodsMapper.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">
<mapper namespace="com.neusoft.mapper.GoodsMapper">
<!-- 按照id查找商品 -->
<select id="getGoodsById" parameterType="int" resultType="Goods">
select
* from goods where goodsId = #{goodsId}
</select>
</mapper>
2、多条件查询商品
测试类
package com.neusoft.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.neusoft.mapper.GoodsMapper;
import com.neusoft.mapper.GoodsTypeMapper;
import com.neusoft.po.Goods;
import com.neusoft.po.GoodsType;
import com.neusoft.util.DBUtil;
public class Test {
public static void main(String[] args) {
SqlSession sqlSession = DBUtil.getSqlSessionFactory().openSession();
GoodsMapper mapper = sqlSession.getMapper(GoodsMapper.class);
System.out.println("=============== 多条件查询商品 ====================");
Goods goodsByC = new Goods();
goodsByC.setGoodsExplain("全网最新");
goodsByC.setGoodsName("小");
goodsByC.setGoodsPrice(1000);
List<Goods> listGoodsByC = mapper.getGoodsByCondition(goodsByC);
for(Goods d : listGoodsByC) {
System.out.println(d);
}
}
}
GoodsMapper接口
//多条件查询商品
package com.neusoft.mapper;
import java.util.List;
import com.neusoft.po.Goods;
public interface GoodsMapper {
//多条件查询商品
public List<Goods> getGoodsByCondition(Goods goods);
}
GoodsMapper.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">
<mapper namespace="com.neusoft.mapper.GoodsMapper">
<!-- 多条件查询商品 -->
<select id="getGoodsByCondition" parameterType="Goods"
resultType="Goods">
select * from goods
<where>
<if test="goodsName!=null and goodsName!=''">
and goodsName like concat('%',#{goodsName},'%')
</if>
<if test="goodsExplain!=null and goodsExplain!=''">
and goodsExplain = #{goodsExplain}
</if>
<if test="goodsPrice!=null and goodsPrice!=''">
and goodsPrice = #{goodsPrice}
</if>
<if test="gtId!=null and gtId!=''">
and gtId = #{gtId}
</if>
</where>
order by goodsId
</select>
</mapper>
3、查找所有商品
测试类
package com.neusoft.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.neusoft.mapper.GoodsMapper;
import com.neusoft.mapper.GoodsTypeMapper;
import com.neusoft.po.Goods;
import com.neusoft.po.GoodsType;
import com.neusoft.util.DBUtil;
public class Test {
public static void main(String[] args) {
System.out.println("=============== 查找所有商品 ====================");
List<Goods> listGoodsAll = mapper.getGoodsAll();
for(Goods d : listGoodsAll) {
System.out.println(d);
}
}
GoodsMapper 接口
package com.neusoft.mapper;
import java.util.List;
import com.neusoft.po.Goods;
public interface GoodsMapper {
//查找所有商品
public List<Goods> getGoodsAll();
}
GoodsMapper .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">
<mapper namespace="com.neusoft.mapper.GoodsMapper">
<!-- 查找所有商品 -->
<select id="getGoodsAll" resultType="Goods">
select * from goods order by
goodsId
</select>
</mapper>
4、修改一条商品数据
测试类
package com.neusoft.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.neusoft.mapper.GoodsMapper;
import com.neusoft.mapper.GoodsTypeMapper;
import com.neusoft.po.Goods;
import com.neusoft.po.GoodsType;
import com.neusoft.util.DBUtil;
public class Test {
public static void main(String[] args) {
System.out.println("=============== 修改一条商品数据 ====================");
Goods goodsEdit = new Goods();
goodsEdit.setGoodsId(2);
goodsEdit.setGoodsExplain("全版本直降100元");
goodsEdit.setGoodsName("小米11");
goodsEdit.setGoodsPrice(2099);
int resultE = mapper.editGoods(goodsEdit);
sqlSession.commit();
System.out.println(resultE);
}
}
GoodsMapper 接口
package com.neusoft.mapper;
import java.util.List;
import com.neusoft.po.Goods;
public interface GoodsMapper {
//修改一条商品数据
public int editGoods(Goods good);
}
GoodsMapper .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">
<mapper namespace="com.neusoft.mapper.GoodsMapper">
<!-- 修改一条商品数据 -->
<update id="editGoods" parameterType="Goods">
update goods
<set>
<if test="goodsName!=null and goodsName!=''">
goodsName = #{goodsName} ,
</if>
<if test="goodsExplain!=null and goodsExplain!=''">
goodsExplain = #{goodsExplain} ,
</if>
<if test="goodsPrice!=null and goodsPrice!=''">
goodsPrice = #{goodsPrice},
</if>
</set>
where goodsId=#{goodsId}
</update>
</mapper>
5、添加商品
测试类
package com.neusoft.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.neusoft.mapper.GoodsMapper;
import com.neusoft.mapper.GoodsTypeMapper;
import com.neusoft.po.Goods;
import com.neusoft.po.GoodsType;
import com.neusoft.util.DBUtil;
public class Test {
public static void main(String[] args) {
System.out.println("=============== 添加商品 ====================");
Goods goodsInsert = new Goods();
goodsInsert.setGtId(1);
goodsInsert.setGoodsExplain("全网最新");
goodsInsert.setGoodsName("小米110");
goodsInsert.setGoodsPrice(1000);
int resultI = mapper.insertGoods(goodsInsert);
sqlSession.commit();
System.out.println(resultI);
}
}
GoodsMapper 接口
package com.neusoft.mapper;
import java.util.List;
import com.neusoft.po.Goods;
public interface GoodsMapper {
//添加
public int insertGoods(Goods good);
}
GoodsMapper .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">
<mapper namespace="com.neusoft.mapper.GoodsMapper">
<!-- 添加商品 -->
<insert id="insertGoods" parameterType="Goods">
insert into goods
<trim prefix="(" suffix=")" suffixOverrides=",">
gtId,
<if test="goodsName!=null and goodsName!=''">
goodsName ,
</if>
<if test="goodsExplain!=null and goodsExplain!=''">
goodsExplain ,
</if>
<if test="goodsPrice!=null and goodsPrice!=''">
goodsPrice ,
</if>
</trim>
<trim prefix="values(" suffix=")" suffixOverrides=",">
#{gtId},
<if test="goodsName!=null and goodsName!=''">
#{goodsName} ,
</if>
<if test="goodsExplain!=null and goodsExplain!=''">
#{goodsExplain} ,
</if>
<if test="goodsPrice!=null and goodsPrice!=''">
#{goodsPrice} ,
</if>
</trim>
</insert>
</mapper>
6、安照id删除一条数据
package com.neusoft.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.neusoft.mapper.GoodsMapper;
import com.neusoft.mapper.GoodsTypeMapper;
import com.neusoft.po.Goods;
import com.neusoft.po.GoodsType;
import com.neusoft.util.DBUtil;
public class Test {
public static void main(String[] args) {
System.out.println("=============== 安照id删除一条数据 ====================");
int resultD = mapper.deleteGoodsById(8);
sqlSession.commit();
System.out.println(resultD);
}
}
GoodsMapper 接口
package com.neusoft.mapper;
import java.util.List;
import com.neusoft.po.Goods;
public interface GoodsMapper {
//安照id删除一条数据
public int deleteGoodsById(Integer goodsId) ;
}
GoodsMapper .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">
<mapper namespace="com.neusoft.mapper.GoodsMapper">
<!-- 安照id删除一条数据 -->
<delete id="deleteGoodsById" parameterType="int">
delete from goods where
goodsId = #{goodsId}
</delete>
</mapper>
7、批量删除商品
测试类
package com.neusoft.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.neusoft.mapper.GoodsMapper;
import com.neusoft.mapper.GoodsTypeMapper;
import com.neusoft.po.Goods;
import com.neusoft.po.GoodsType;
import com.neusoft.util.DBUtil;
public class Test {
public static void main(String[] args) {
System.out.println("=============== 批量删除商品 ====================");
Integer[] goodsIds = {9,10,11};
int resultDB = mapper.deleteGoodsBatch(goodsIds);
sqlSession.commit();
System.out.println( resultDB );
}
}
GoodsMapper 接口
package com.neusoft.mapper;
import java.util.List;
import com.neusoft.po.Goods;
public interface GoodsMapper {
//批量删除商品
public int deleteGoodsBatch(Integer goodsIds[]);
}
GoodsMapper .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">
<mapper namespace="com.neusoft.mapper.GoodsMapper">
<!-- 批量删除商品 -->
<delete id="deleteGoodsBatch" parameterType="Integer">
delete from goods where goodsId in
<foreach collection="array" item="goodsIds" open="(" close=")"
separator=",">
#{goodsIds}
</foreach>
</delete>
</mapper>
8、按照id查找商品并显示其所属分类信息(单独查询)
测试类
package com.neusoft.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.neusoft.mapper.GoodsMapper;
import com.neusoft.mapper.GoodsTypeMapper;
import com.neusoft.po.Goods;
import com.neusoft.po.GoodsType;
import com.neusoft.util.DBUtil;
public class Test {
public static void main(String[] args) {
Goods goodsByIdOfGoodsType = mapper.getGoodsByIdOfGoodsType(1);
System.out.println("======== 按照id查找商品并显示其所属分类信息(单独查询) ======");
System.out.println(goodsByIdOfGoodsType);
}
}
GoodsMapper 接口
package com.neusoft.mapper;
import java.util.List;
import com.neusoft.po.Goods;
public interface GoodsMapper {
//按照id查找商品并显示其所属分类信息(单独查询)
public Goods getGoodsByIdOfGoodsType(Integer goodsId);
}
GoodsMapper .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">
<mapper namespace="com.neusoft.mapper.GoodsMapper">
<!-- 按照id查找商品并显示其所属分类信息(单独查询) -->
<resultMap type="Goods" id="GTOnlyResultMap">
<id property="goodsId" column="goodsId" />
<result property="goodsName" column="goodsName" />
<result property="goodsExplain" column="goodsExplain" />
<result property="goodsPrice" column="goodsPrice" />
<result property="gtId" column="gtId" />
<association property="goodsType" javaType="GoodsType"
select="com.neusoft.mapper.GoodsTypeMapper.getGoodsTypeById"
column="gtId" />
</resultMap>
<select id="getGoodsByIdOfGoodsType" parameterType="int"
resultMap="GTOnlyResultMap">
select * from goods where goodsId = #{goodsId}
</select>
</mapper>
GoodsTypeMapper.xml
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.neusoft.mapper.GoodsTypeMapper">
<!-- 按照id查找商品分类 -->
<select id="getGoodsTypeById" parameterType="int" resultType="GoodsType">
select * from goodstype where gtId = #{gtId}
</select>
</mapper>
9、查找所有商品并显示其所属分类信息(一起查询)
测试类
package com.neusoft.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.neusoft.mapper.GoodsMapper;
import com.neusoft.mapper.GoodsTypeMapper;
import com.neusoft.po.Goods;
import com.neusoft.po.GoodsType;
import com.neusoft.util.DBUtil;
public class Test {
public static void main(String[] args) {
System.out.println("===== 查找所有商品并显示其所属分类信息(一起查询) =======");
List<Goods> listgoodsOfG = mapper.getGoodsOfGoodsType();
for(Goods d : listgoodsOfG) {
System.out.println(d);
}
}
}
GoodsMapper 接口
package com.neusoft.mapper;
import java.util.List;
import com.neusoft.po.Goods;
public interface GoodsMapper {
//查找所有商品并显示其所属分类信息(一起查询)
public List<Goods> getGoodsOfGoodsType();
}
GoodsMapper .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">
<mapper namespace="com.neusoft.mapper.GoodsMapper">
<!-- 查找所有商品并显示其所属分类信息(一起查询) -->
<resultMap type="Goods" id="GTResultMap">
<id property="goodsId" column="goodsId" />
<result property="goodsName" column="goodsName" />
<result property="goodsExplain" column="goodsExplain" />
<result property="goodsPrice" column="goodsPrice" />
<result property="gtId" column="gtId" />
<association property="goodsType" javaType="GoodsType">
<id property="gtId" column="gtId" />
<result property="gtName" column="gtName" />
<result property="gtExplain" column="gtExplain" />
</association>
</resultMap>
<select id="getGoodsOfGoodsType" resultMap="GTResultMap">
select g.*,
gt.gtId,
gt.gtName,
gt.gtExplain
from goods g left join goodstype gt
on
g.gtId=gt.gtId
</select>
</mapper>
10、查找所有分类下的所有商品(一条sql一起查)
测试类
package com.neusoft.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.neusoft.mapper.GoodsMapper;
import com.neusoft.mapper.GoodsTypeMapper;
import com.neusoft.po.Goods;
import com.neusoft.po.GoodsType;
import com.neusoft.util.DBUtil;
public class Test {
public static void main(String[] args) {
SqlSession sqlSession = DBUtil.getSqlSessionFactory().openSession();
GoodsTypeMapper gtmapper = sqlSession.getMapper(GoodsTypeMapper.class);
System.out.println("===== 查找所有分类下的所有商品(一条sql一起查) ========");
List<GoodsType> listGoodsOfGoodsType = gtmapper.getGoodsOfGoodsType();
for(GoodsType d : listGoodsOfGoodsType) {
System.out.println(d);
}
}
}
GoodsTypeMapper 接口
package com.neusoft.mapper;
import java.util.List;
import com.neusoft.po.GoodsType;
public interface GoodsTypeMapper {
//查找所有分类下的所有商品(一条sql一起查)
public List<GoodsType> getGoodsOfGoodsType();
}
GoodsTypeMapper .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">
<mapper namespace="com.neusoft.mapper.GoodsTypeMapper">
<!-- 查找所有商品并显示其所属分类信息(一起查询) -->
<resultMap type="GoodsType" id="GTResultMap">
<id property="gtId" column="gtId" />
<result property="gtName" column="gtName" />
<result property="gtExplain" column="gtExplain" />
<collection property="goods" ofType="Goods">
<id property="goodsId" column="goodsId" />
<result property="goodsName" column="goodsName" />
<result property="goodsExplain" column="goodsExplain" />
<result property="goodsPrice" column="goodsPrice" />
<result property="gtId" column="gtId" />
</collection>
</resultMap>
<select id="getGoodsOfGoodsType" resultMap="GTResultMap">
select gt.*,
g.goodsId,
g.goodsName,
g.goodsExplain,
g.goodsPrice,
g.gtId
from goodstype
gt left join goods g
on
g.gtId=gt.gtId
</select>
</mapper>
11、查找所有分类下的所有商品(单独查)
测试类
package com.neusoft.test;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import com.neusoft.mapper.GoodsMapper;
import com.neusoft.mapper.GoodsTypeMapper;
import com.neusoft.po.Goods;
import com.neusoft.po.GoodsType;
import com.neusoft.util.DBUtil;
public class Test {
public static void main(String[] args) {
System.out.println("==== 查找所有分类下的所有商品(单独查) ====");
List<GoodsType> listgetGoodsTypeByIdOfGoods = gtmapper.getGoodsTypeOfGoods();
for(GoodsType d : listgetGoodsTypeByIdOfGoods) {
System.out.println(d);
}
}
}
GoodsTypeMapper 接口
package com.neusoft.mapper;
import java.util.List;
import com.neusoft.po.GoodsType;
public interface GoodsTypeMapper {
//查找所有分类下的所有商品(单独查)
public List<GoodsType> getGoodsTypeOfGoods();
}
GoodsTypeMapper.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">
<mapper namespace="com.neusoft.mapper.GoodsTypeMapper">
<!-- 查找所有分类下的所有商品(单独查) -->
<resultMap type="GoodsType" id="goodsTypeOfGoodsResultMap">
<id property="gtId" column="gtId" />
<result property="gtName" column="gtName" />
<result property="gtExplain" column="gtExplain" />
<collection property="goods" ofType="Goods"
select="com.neusoft.mapper.GoodsMapper.getGoodsTypeByGTId" column="gtId" />
</resultMap>
<select id="getGoodsTypeOfGoods" parameterType="int" resultMap="goodsTypeOfGoodsResultMap">
select * from goodstype
</select>
</mapper>
GoodsMapper.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">
<mapper namespace="com.neusoft.mapper.GoodsMapper">
<!-- 按照分类id查找商品 -->
<select id="getGoodsTypeByGTId" parameterType="int" resultType="Goods">
select * from goods where gtId = #{gtId}
</select>
</mapper>