Mybatis(三)——Mapper编写的⼏种⽅式、动态SQL、分页查询、特殊字符处
制作查询类小程序理、⽀。。。
⽂章⽬录
回顾
接⼝+l操作数据库
Mapper编写有⼏种⽅式?
1. 接⼝实现类集成SQLSessionDaoSupport 此⽅法需要编写mapper接⼝,mapper接⼝的实现类,l⽂件。
2. 使⽤batis.spring.mapper.MapperFactoryBean 此⽅法需要在l中配置l的位置,还需定义
mapper接⼝。
3. 使⽤mapper扫描器 需要编写l⽂件,需要mapper接⼝,配置mapper扫描器,使⽤扫描器
从spring容器中获取mapper
的实现对象。
案例演⽰
总结: 使⽤Mybatis的mapper接⼝调⽤时候有哪些要求?
1. Mapper接⼝⽅法名和l中定义的每个SQL的id相同;
2. Mapper接⼝⽅法的输⼊参数类型和l中定义的每个sqlparameterType类型相同
3. Mapper接⼝⽅法的输出参数类型和l中定义的sql的resultType的类型相同
4. l⽂件中的namespace,就是接⼝的类路径。
有两个问题值得注意,第⼀是接⼝名必须和映射⽂件名⼀致,第⼆是接⼝⽂件和l的位置必须放置在同⼀⽬录下,只有这样MyBatis才会⾃动扫描,把接⼝和映射⽂件相匹配。否则,就要在全局配置⽂件中对接⼝和映射⽂件分别进⾏配置。这⾥我们推荐⾃动扫描,即把l和接⼝⽂件放在同⼀⽬录下,配置时只需要扫描接⼝⽂件就可以了。
话不多说,继MyBatis(⼀)中的⼩程序,我们现在来新建⼀ProductMapper.java接⼝,此时的⽬录信息如下:
接着去全局配置⽂件中进⾏配置:
<mappers>
<mapper class="apper.ProductMapper"/>
</mappers>
我们测试时按照从 映射⽂件——接⼝——测试类——控制台 的顺序依次编写代码:
映射⽂件:新增商品信息
<insert id="insertProductInfo"parameterType="product">
insert into t_product values(
#{id},
#{name},
#{code},
#{price},
#{count},
#{description},
#{status},
#{create_time}
);
</insert>
接⼝
apper;
ity.Product;
public interface ProductMapper {
// 接⼝中定义⽅法,⽅法名和映射⽂件中的sql语句id尽量保持⼀致,该有的参数也要定义出来
public void insertProductInfo(Product product);
}
测试类
st;
import java.io.IOException;
import java.util.Date;
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 org.junit.Test;
ity.Product;
apper.ProductMapper;
public class MyTest2 {
@Test
public void testInsertProductInfo()throws IOException {
// 1.获取到SqlSessionFactory对象
SqlSessionFactory sessionFactory =new SqlSessionFactoryBuilder() .ResourceAsReader("l"));
// 2.获取SqlSession对象
SqlSession session = sessionFactory.openSession();
// 3.通过接⼝的class⽂件获得mapper
ProductMapper mapper = Mapper(ProductMapper.class); // 4.创建product对象
Product product =new Product();
product.setName("魅族⼿机");
product.setCode("10009");
product.setPrice(4000.00);
product.setCount(10);
product.setDescription("国产⼿机品牌");
product.setStatus(1);
product.setCreate_time(new Date());
// 5.mapper执⾏sql语句
mapper.insertProductInfo(product);
// 6.⼿动提交事务
sessionmit();
// 7.释放资源
session.close();
}
}
控制台
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
PooledDataSource forcefully closed/removed all connections.
Opening JDBC Connection
Created connection 922872566.
Setting autocommit to false on JDBC Connection [sql.jdbc.JDBC4Connection@3701eaf6]
==>  Preparing: insert into t_product values(?,?,?,?,?,?,?,?);
==> Parameters: null,魅族⼿机(String),10009(String),4000.0(Double),10(Integer),国产⼿机品牌(String),1(Integer),2019-04-1900:36:54.986(Timestamp )
<==    Updates:1
Committing JDBC Connection [sql.jdbc.JDBC4Connection@3701eaf6]
Resetting autocommit to true on JDBC Connection [sql.jdbc.JDBC4Connection@3701eaf6]
Closing JDBC Connection [sql.jdbc.JDBC4Connection@3701eaf6]
Returned connection 922872566 to pool.
这样,我们就完成了利⽤接⼝+l⽂件来操作数据库,其他的增删改查与之类似,不再赘述。
利⽤注解传递参数
相信你已经发现了,前⾯我们所讲在sql语句需要多个参数时,我们都⼲脆直接传递过来⼀个封装好的javabean对象,这种⽅法适⽤于sql语句需要多个参数时,但是当只有两三个参数时,还要封装成对象传过来未免有些⿇烦。现在我们学习⽤注解传递参数来解决这个问题:
⽐如现在我想通过id来更改价格,那么必不可少的两个参数是id和价格:
映射⽂件
<!--我们利⽤注解来传递参数,这⾥就不需要设置parameterType了-->
<!--不过要注意映射⽂件中和接⼝的声明的参数名即value要⼀致-->
<update id="updatePriceById">
update t_product set price=#{price} where id = #{id}
</update>
接⼝
public void updatePriceByID(@Param(value="price")Double price,
@Param(value="id")Integer id);
测试类
@Test
public void testUpdateProductById()throws IOException {
// 获取到SqlSessionFactory对象
SqlSessionFactory sessionFactory =new SqlSessionFactoryBuilder()
.ResourceAsReader("l"));
// 获取SqlSession对象
SqlSession session = sessionFactory.openSession();
// 通过接⼝的class⽂件获得mapper
ProductMapper mapper = Mapper(ProductMapper.class);
// 根据id来更改价格
mapper.updatePriceById(5000.00,3);
// ⼿动提交事务
sessionmit();
// 释放资源
session.close();
}
控制台
==>  Preparing: update t_product set price=? where id=?
==> Parameters:5000.0(Double),3(Integer)
<==    Updates:1
MyBatis常⽤注解
@Insert : 插⼊sql , 和xml insert sql语法完全⼀样
@Select : 查询sql, 和xml select sql语法完全⼀样
@Update : 更新sql, 和xml update sql语法完全⼀样
@Delete : 删除sql, 和xml delete sql语法完全⼀样
@Param : ⼊参
@Results :结果集合
@Result : 结果
模糊查询
下⾯我们来学习怎么进⾏模糊查询,⽐如我想执⾏这句SQL语句:
select*from t_product where name like'%⽶%'
其实模糊查询跟普通的查询并没有太⼤的区别,值得注意的是’%'与字符的拼接。关于字符串的拼接,我们可以在传参时在测试类中拼接好传过来,也可以在sql语句执⾏时拼接。
映射⽂件
<select id="selectProductByLike"parameterType="String"resultType="product">
select * from t_product where name like #{value}
</select>
接⼝
@Test
public void testSelectProductByLike()throws IOException {
SqlSessionFactory sessionFactory =new SqlSessionFactoryBuilder()
.ResourceAsReader("l"));
SqlSession session = sessionFactory.openSession();
ProductMapper mapper = Mapper(ProductMapper.class);
// 直接把拼接好的字符串传过去
List<Product> productByLike = mapper.selectProductByLike("%⽶%");
sessionmit();
session.close();
}
控制台
==>  Preparing: select * from t_product where name like ?
==> Parameters:%⽶%(String)
<==    Columns: id, name, code, price, count, description, status, create_time
<==        Row:3,⼩⽶⼿机,10002,5000,20,国产⼿机品牌,1,2019-04-1814:04:56.0
<==      Total:1
这种⼿动拼接的⽅法不友好,不推荐使⽤,我们的希望是实现⾃动拼接:
……
String name ="⽶";
List<Product> productByLike = mapper.selectProductByLike("%"+name+"%");
……

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。