MyBatis动态条件、一对多、整合spring(二)
输入映射和输出映射
Mapper.xml映射文件定义了操作数据库的sql,每一个sql是一个statement,映射文件是mybatis的核心。
parameterType输入类型
1.传递简单类型
Integer、String 使用#{}占位符 | ${}拼接字符
parameterType="Integer"
parameterType="String"
2.传递pojo对象
Product类
parameterType="com.bean.Product"
3.传递pojo包装对象
开发过程中,我们可以通过传递pojo当做查询条件,而查询用户的userid时又要查询订单表的order信息,这时定义成一个包装类作为参数传递。
新建QueryVo类
package com.bean;
import com.sun.tools.internal.xjc.reader.xmlschema.bindinfo.BIConversion;
public class QueryVo {
private BIConversion.User user;
public BIConversion.User getUser() {
return user;
}
public void setUser(BIConversion.User user) {
this.user = user;
}
}
配置mapper.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.mapper.ProductMapper">
<select id="getProduct" parameterType="Integer" resultType="com.bean.Product">
select * from Product where Id = #{id}
</select>
<select id="getProductListByName" parameterType="String" resultType="com.bean.Product">
select * from Product where name like "%"#{haha}"%"
</select>
<select id="getProductListByQueryVo" parameterType="com.bean.QueryVo" resultType="com.bean.Product">
select * from Product where name like "%"#{product.name}"%"
</select>
</mapper>
编写测试方法
@Test
public void getProductListByQueryVo(){
String resource = "SqlMapConfig.xml";
InputStream is = Main.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession session = sessionFactory.openSession();
ProductMapper mapper = session.getMapper(ProductMapper.class);
QueryVo vo = new QueryVo();
com.bean.Product p = new com.bean.Product();
p.setName("桃");
vo.setProduct(p);
List<Product> list = mapper.getProductListByQueryVo(vo);
for(Product l : list){
System.out.print(l);
}
}
resultType输出类型
1.输出简单类型
<select id="getProductCount" resultType="Integer">
select count(*) from Product
</select>
public interface ProductMapper {
Product getProduct(Integer id);
List<Product> getProductListByQueryVo(QueryVo queryVo);
int getProductCount();
}
@Test
public void getProductCount(){
String resource = "SqlMapConfig.xml";
InputStream is = Main.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession session = sessionFactory.openSession();
ProductMapper mapper = session.getMapper(ProductMapper.class); int count = mapper.getProductCount();
System.out.print(count);
}
2.输出pojo对象和pojo集合(参考上一篇)
<select id="getProduct" parameterType="Integer" resultType="com.bean.Product">
select * from Product where Id = #{id}
</select>
<select id="getProductListByName" parameterType="String" resultType="com.bean.Product">
select * from Product where name like "%"#{haha}"%"
</select>
3.resultMap
resultType可以指定将查询结果映射为pojo,但需要pojo的属性名和sql查询的列一致方可映射成功。
如果sql查询字段名和pojo属性名不一致,可以通过resultMap将字段名和属性做一个对应关系,resultMap是指上还需要将查询结果映射到pojo对象中。
resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对多查询和一对一查询。
新建实体类,mapper.xml,接口,和测试方法如下:
package com.bean;
public class BigProduct {
private Integer bigPId;
private String bigPname;
private String bigPprice;
...
}
<?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.mapper.BigProductMapper">
<select id="getProductList" resultMap="bigProductMap">
select id,name,price from Product
</select> <resultMap id="bigProductMap" type="com.bean.BigProduct">
<!--property主键在pojo中属性名
column 数据库中字段名-->
<id property="bigPId" column="id"></id>
<!--定义其他属性 如与属性名一致可以不写 -->
<result property="bigPname" column="name"></result>
<result property="bigPprice" column="price"></result>
</resultMap>
</mapper>
package com.mapper;
import com.bean.BigProduct;
import java.util.List;
public interface BigProductMapper {
List<BigProduct> getProductList();
}
@Test
public void getBigProductList(){
String resource = "SqlMapConfig.xml";
InputStream is = Main.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is); SqlSession session = sessionFactory.openSession();
BigProductMapper mapper = session.getMapper(BigProductMapper.class);
List<BigProduct> productList = mapper.getProductList();
for(BigProduct bp : productList){
System.out.print(bp);
}
}
动态sql
while if 标签-不用写where 1==1 去考虑后面的and
<select id="getProductListByName" parameterType="com.bean.Product" resultType="com.bean.Product">
select * from Product
<where>
<if test="name != null or name != ''">
and name like "%"#{name}"%"
</if>
</where>
</select>
sql片段-可以将重复的sql提取出来,使用时用include引用即可。
<sql id="queryProduct">
select * from Product
</sql>
<select id="getProductListByName" parameterType="com.bean.Product" resultType="com.bean.Product">
<include refid="queryProduct"></include>
<where>
<if test="name != null or name != ''">
and name like "%"#{name}"%"
</if>
</where>
</select>
foreach标签-像sql传递数组或list,mybatis使用foreach解析如 id in (1,2,3,4)
修改QueryVo 使其支持list ids 存储多个id,并添加getter/setter方法
package com.bean;
import java.util.List;
public class QueryVo {
private Product product;
private List<Integer> ids;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
}
mapper.xml
<select id="getProductByIds" parameterType="com.bean.QueryVo" resultType="com.bean.Product">
select * from product
<where>
<!--colletion:遍历的集合
item:遍历集合的变量
open:在前面添加sql片段
close:结束添加sql片段
separator:使用的分隔符-->
<foreach collection="ids" item="item" open="id in (" close=")" separator=",">
#{item}
</foreach>
</where>
</select>
接口
public interface ProductMapper {
List<Product> getProductByIds(QueryVo queryVo);
测试
@Test
public void getProductByIds(){
String resource = "SqlMapConfig.xml";
InputStream is = Main.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sessionFactory.openSession();
ProductMapper mapper = session.getMapper(ProductMapper.class); QueryVo queryVo = new QueryVo();
List<Integer> ids = new ArrayList<Integer>();
ids.add(1);
ids.add(3);
ids.add(9);
queryVo.setIds(ids); List<Product> list = mapper.getProductByIds(queryVo);
System.out.print(list);
}
关联查询
一对一查询:
商品分类 和商品表 是一对多关系 反之 是一对一关系 读取商品获取其对应分类
在Product类中加入Category类属性
public class Product {
private Integer Id;
private String Name;
private String price;
private Category category;
...
mapper.xml
<mapper namespace="com.mapper.ProductMapper">
<resultMap id="productCategoryResultMap" type="com.bean.Product">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="price" column="price"></result>
<!--配置一对一属性 -->
<association property="category" javaType="com.bean.Category">
<id property="id" column="categoryId"></id>
<result property="name" column="name"></result>
</association>
</resultMap>
<select id="getProductCategory" resultMap="productCategoryResultMap">
select p.id,p.name,p.price,p.categoryId,c.name from Product p
left join category c on p.categoryId = c.id;
</select>
测试
@Test
public void getProductCategory(){
String resource = "SqlMapConfig.xml";
InputStream is = Main.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sessionFactory.openSession();
ProductMapper mapper = session.getMapper(ProductMapper.class);
List<Product> pcs = mapper.getProductCategory();
for(Product pc : pcs){
System.out.println(pc);
}
}
一对多查询:
在Category类中增加List<product> products属性并生成getset方法
public class Category {
private Integer id;
private String name;
private List<Product> products;
mapper.xml
<mapper namespace="com.mapper.ProductMapper">
<resultMap id="categoryProducts" type="com.bean.Category">
<id property="id" column="categoryId"></id>
<result property="name" column="name"></result>
<!--配置一对多 -->
<collection property="products" javaType="list" ofType="com.bean.Product">
<id property="id" column="id"></id>
<result property="name" column="name"></result>
<result property="price" column="price"></result>
</collection>
</resultMap>
<select id="categoryProducts" resultMap="categoryProducts">
select c.name,p.id,p.name,p.price,p.categoryId from category c
left join Product p on c.id = p.categoryId;
</select>
测试
@Test
public void categoryProducts(){
String resource = "SqlMapConfig.xml";
InputStream is = Main.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
SqlSession session = sessionFactory.openSession();
ProductMapper mapper = session.getMapper(ProductMapper.class);
List<Category> list = mapper.categoryProducts();
for(Category c : list){
System.out.print(c);
for(Product p : c.getProducts()){
System.out.print(p);
}
}
System.out.print(list); }
Mybatis整合spring
将sessionFactory对象放到spring容器中,由spring帮我们创建session对象,及mapper对象。
1.导包 spring的jar包,mybatis的jar包,spring+mybatis的整合包,mysql数据库驱动包,数据库连接池的jar包。
2.添加SqlMapConfig.xml ,applicationContext.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>
<!-- 设置别名 -->
<typeAliases>
<package name="com.bean" />
</typeAliases> </configuration>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" /> <!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean> <!-- 配置SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 配置mybatis核心配置文件 -->
<property name="configLocation" value="classpath:SqlMapConfig.xml" />
<!-- 配置数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/david2018_db?characterEncoding=utf-8
jdbc.username=root
jdbc.password=1234
log4j.properties
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
传统dao的开发方式,创建接口,创建实现类,实现类继承SqlsessionDaoSupport类来获得session对象操作。不做演示了。
Mapp代理形式开发dao
编写ProductMapper.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.mapper.ProductMapper">
<select id="getProduct" parameterType="Integer" resultType="com.bean.Product">
select * from Product where Id = #{id}
</select>
<select id="getProductListByName" parameterType="com.bean.Product" resultType="com.bean.Product">
<include refid="queryProduct"></include>
<where>
<if test="name != null or name != ''">
and name like "%"#{name}"%"
</if>
</where>
</select>
<insert id="insertProduct" parameterType="com.bean.Product">
<selectKey keyProperty="id" resultType="Integer" order="AFTER">
select last_insert_id()
</selectKey>
insert into Product (name,price) values (#{name},#{price})
</insert>
<update id="updateById" parameterType="com.bean.Product">
update Product set name = #{name} , price=#{price} where id = #{id}
</update>
<delete id="deleteById" parameterType="Integer">
delete from Product where id = #{id}
</delete>
</mapper>
实现ProductMapper接口
package com.mapper;
import com.bean.*;
import java.util.List;
public interface ProductMapper {
Product getProduct(Integer id);
List<Product> getProductListByName(Product p);
void insertProduct(Product p);
void updateById(Product p);
void deleteById(Integer id);
}
加载mapper.xml文件到核心配置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>
<!-- 设置别名 -->
<typeAliases>
<package name="com.bean"/>
</typeAliases>
<mappers>
<mapper resource="com/mapper/ProductMapper.xml"></mapper>
</mappers>
</configuration>
配置mapper代理-在applicationContext.xml中
<!-- Mapper代理的方式开发方式一,配置Mapper代理对象 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<!-- 配置Mapper接口 -->
<property name="mapperInterface" value="com.mapper.ProductMapper" />
<!-- 配置sqlSessionFactory -->
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
或者扫描所有mapper文件夹
<!-- Mapper代理的方式开发方式二,扫描包方式配置代理 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 配置Mapper接口 -->
<property name="basePackage" value="com.mapper" />
</bean>
测试方法:
package com.company; import com.bean.Product;
import com.mapper.ProductMapper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.List; public class Main {
private ApplicationContext context; @Before
public void setUp(){
this.context = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
} @Test
public void getProduct(){
ProductMapper mapper = this.context.getBean(ProductMapper.class);
Product p = mapper.getProduct(1);
System.out.print(p);
} @Test
public void getProductListByName(){
ProductMapper mapper = this.context.getBean(ProductMapper.class);
Product pro = new Product();
pro.setName("桃");
List<Product> p = mapper.getProductListByName(pro);
System.out.print(p);
} }
MyBatis动态条件、一对多、整合spring(二)的更多相关文章
- SSM实战——秒杀系统之DAO层实体定义、接口设计、mybatis映射文件编写、整合Spring与Mybatis
一:DAO实体编码 1:首先,在src目录下,新建org.myseckill.entity包,用于存放实体类: 2:实体类设计 根据前面创建的数据库表以及映射关系,创建实体类. 表一:秒杀商品表 对应 ...
- mybatis动态条件组合分页查询
一.动态条件处理 需要使用mybatis的动态sql 1 <select id="selectItemByCondition" parameterType="com ...
- JAVAEE——Mybatis第二天:输入和输出映射、动态sql、关联查询、Mybatis整合spring、Mybatis逆向工程
1. 学习计划 1.输入映射和输出映射 a) 输入参数映射 b) 返回值映射 2.动态sql a) If标签 b) Where标签 c) Sql片段 d) Foreach标签 3.关联查询 a) 一对 ...
- mybatis入门_一对多,多对多映射以及整合spring框架
一.一对多映射. 1.1 一对多映射之根据多的一方关联查询一的一方 示例:查询出具体的订单信息,同时也查询出来订单的用户信息. 引入的订单表如下所示: 框选出来的为具体的外键. 订单的Pojo类如下所 ...
- OSGI企业应用开发(九)整合Spring和Mybatis框架(二)
上篇文章中,我们完成了在OSGI应用中整合Spring和Mybatis框架的准备工作,本节我们继续Spring和Mybatis框架的整合. 一.解决OSGI整合Spring中的Placeholder问 ...
- Spring学习笔记:Spring整合Mybatis(mybatis-spring.jar)(二:mybatis整合spring)
http://blog.csdn.net/qq598535550/article/details/51703190 二.Spring整合mybatis其实是在mybatis的基础上实现Spring框架 ...
- Spring Boot整合Mybatis完成级联一对多CRUD操作
在关系型数据库中,随处可见表之间的连接,对级联的表进行增删改查也是程序员必备的基础技能.关于Spring Boot整合Mybatis在之前已经详细写过,不熟悉的可以回顾Spring Boot整合Myb ...
- 搭建Spring + SpringMVC + Mybatis框架之二(整合Spring和Mybatis)
整合Spring和Mybatis 首先给出完整的项目目录: (1)引入项目需要的jar包 使用http://maven.apache.org作为中央仓库即可. Spring核心包,mybatis核心包 ...
- JAVAEE——宜立方商城09:Activemq整合spring的应用场景、添加商品同步索引库、商品详情页面动态展示与使用缓存
1. 学习计划 1.Activemq整合spring的应用场景 2.添加商品同步索引库 3.商品详情页面动态展示 4.展示详情页面使用缓存 2. Activemq整合spring 2.1. 使用方法 ...
随机推荐
- 创建pod索引库(Specs)
专门用来存放xxx.podspec 的索引文件的库就叫做索引库.我们需要将这些索引文件上传到远程索引库才能保证其他的人能够拿来用. 创建一个远程索引库和本地索引库对应起来,步骤如下: 1.登录开源中国 ...
- iview中Modal弹窗做form表单验证相关问题
在modal中初始化状态,点击确定弹窗消失. 有的时候表单验证就不希望立刻消失 在iview官网中有自定义页头页脚 可以直接自定义使用 另一种验证写法 serform: { ctCatelogue: ...
- 7-9 旅游规划 (25 分)(Dijkstra算法)
题意: 思路:单源最短路问题,Dijkstra算法搞定就可以了,因为要找出最便宜的最短路,所以需要在更新最短距离的时候加一个条件(即当最短距离相等的时候,如果该路径的花费更小,就更新最小花费)就可 ...
- 第一节:web爬虫之requests
Requests库是用Python编写的,并且Requests是一个优雅而简单的Python HTTP库,在使用Requests库时更加方便,可以节约我们大量的工作,完全满足HTTP测试需求.
- 8.1.2 Cursor 对象
游标Cursor也是sqlite3模块中比较重要的一个类,下面简单介绍下Cursor对象的常用方法. 1 execute(sql[,parameters]) 该方法用于执行一条SQL语句,下面的代码演 ...
- Spring MVC 单元测试Demo
@RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations={" ...
- unigui菜单【3】
unigui菜单TuniTreeView 根据数据库表中的内容,显示菜单的处理: function TMainForm.CreateMenu: Integer; var myMenuPoint : P ...
- Java基础学习总结(73)——Java最新面试题汇总
1.super()与this()的区别? this():当前类的对象,super父类对象. super():在子类访问父类的成员和行为,必须受类继承规则的约束 而this他代表当前对象,当然所有的资源 ...
- Java基础学习总结(71)——深入理解Java虚拟机内存
Java虚拟机中的内存分配图 : 各个区域的特性总结如下表: 补充说明: 当多线程情形下,可能多个线程要在堆上分配内存,那么可能出现内存分配的同步问题,解决方案有两个,一个就是同步内存分配动作:另一个 ...
- maven local responsitory 手工新增jar
1.推荐几个好的 Maven 常用仓库网址:http://mvnrepository.com/http://search.maven.org/http://repository.sonatype.or ...