Mybatis输入类型和结果类型
1.结果集resultMap映射
解决数据库中字段名称和定义的类中的属性名称不一致
<!--
结果集映射:
id: 为了结果映射起个id
type: 为了哪个实体类
-->
<resultMap id="userMap" type="user">
<!--
property 声明jaavBean属性名
column 声明数据库查询出来的结果集对应列名 (考虑别名)
-->
<result property="id" column="uid"></result>
<result property="username" column="name"></result>
<result property="gender" column="gender"></result>
<result property="birthday" column="birthday"></result>
<result property="address" column="address"></result>
</resultMap>
<select id="findById1" parameterType="int" resultMap="userMap">
select id AS uid,NAME,gender,birthday,address from user where id=#{id}
</select>
2.输入多个参数
<!--
根据用户名和地址查询
传过来一个user对象
取出对应属性值
#{javaBean属性名}
-->
<select id="findByUsernameAndAddress" parameterType="user" resultMap="userMap">
select id AS uid,NAME,gender,birthday,address from user where name=#{username} AND address=#{address}
</select>
3.复合查询
@Test
public void testfindByCondition2(){
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = builder.build(AppTest.class.getClassLoader().getResourceAsStream("SqlMapConfig.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession();
ProductDao productDao = sqlSession.getMapper(ProductDao.class);
ProductQuery productQuery = new ProductQuery();
Product product = new Product();
product.setChicun(6);
Category category = new Category();
category.setCname("手机数码");
productQuery.setCategory(category);
productQuery.setProduct(product);
List<Product> byCondition2 = productDao.findByCondition2(productQuery);
System.out.println(byCondition2);
sqlSession.close();
}
<select id="findByCondition2" parameterType="productQuery" resultType="product">
select * from product where cid=(
select cid from category where cname=#{category.cname}
)
and chicun=#{product.chicun}
</select>
package com.shenhao.domain;
import com.shenhao.domain.Category;
import com.shenhao.domain.Product;
public class ProductQuery {
private Product product;
private Category category;
public Product getProduct() {
return product;
}
public Category getCategory() {
return category;
}
public void setProduct(Product product) {
this.product = product;
}
public void setCategory(Category category) {
this.category = category;
}
}