如何在MyBatis的l中sql语句实现批量新增以及更新操作?我这⾥建⽴了⼀个vo类,继承了书本类(⾥⾯可以写你⾃⼰需要的东西,很⽅便)
// 这⾥⽤来注解,所以没有get和set以及toString
@Data
public class BookVo extends Book {
private List<Book> books;
}
然后再就是接⼝⾥⾯的⽅法的定义
/**
* 批量新增书本
* @param bookVo
* @return
*/
int addBatchBooks(BookVo bookVo);
//批量更新
int updateBatchBookS(BookVo bookVo);
<!--批量新增-->
<insert id="addBatchBooks" parameterType="batis01.vo.BookVo">
insert into t_book(bookname,price,booktype,bookimage)
<!--
2.open:开始位置
3.close:结束位置
4.separator:分符号
5.item:遍历的⼦项
6.index:索引
这个也是⼀种⽅式也可以⽤:
foreach(int i in lst)
<foreach collection="books" item="b" open=" values(" close=")" separator="),(">
#{b.bookname},#{b.price},#{b.booktype},#{b.bookimage}
</foreach>
-->
<foreach collection="books" item="b" open=" values" separator=",">
(#{b.bookname},#{b.price},#{b.booktype},#{b.bookimage})
</foreach>
</insert>
<!--批量更新-->
<update id="updateBatchBookS" parameterType="batis01.vo.BookVo">
<foreach collection="books" item="b" separator=";">
update t_book
<set>
<if test="b.bookname != null">
bookname = #{b.bookname},
</if>
<if test="b.price != null">
price = #{b.price},
</if>
<if test="b.booktype != null">
booktype = #{b.booktype},
</if>
<if test="b.bookimage != null">
bookimage = #{b.bookimage},
</if>
</set>
where id = #{b.id}
</foreach>
</update>
Junit测试类⾥⾯⽅法的运⾏
public class BookServicesImplTest {
private IBookServices bookService;
private SqlSession sqlSession;
private Book book;
@Before
public void setUp() throws Exception {
批量更新sql语句sqlSession = MybatisSessionFactoryUtils.openSession();
BookMapper bookMapper = Mapper(BookMapper.class);
BookServicesImpl bookServiesImpl=new BookServicesImpl();
bookServiesImpl.setBookMapper(bookMapper);
this.bookService=bookServiesImpl;
book =new Book();
}
@After
public void tearDown() throws Exception {
sqlSessionmit();
MybatisSessionFactoryUtils.closeSession();
}
@Test
public void Test(){
//批量新增
BookVo bv=new BookVo();
List<Book> bookList=new ArrayList<Book>();
for(int i =0; i <5; i++){
Book b=new Book();
b.setBookname("德鲁纳酒店"+i+"集");
b.setPrice(128f);
b.setBooktype("爱情⽞幻");
b.setBookimage("dlnjd.jpg");
bookList.add(b);
}
bv.setBooks(bookList);
bookService.addBatchBooks(bv);
//批量修改
/*BookVo bv=new BookVo();
List<Book> bookList=new ArrayList<Book>();
for (int i = 0; i <5; i++) {
Book b=new Book();
b.setId(i);
b.setBookname("魔道祖师"+i+"集");
b.setPrice(128f);
b.setBooktype("修仙⽞幻");
b.setBookimage("mdzs.jpg");
bookList.add(b);
}
bv.setBooks(bookList);
bookService.updateBatchBookS(bv);*/
/* book.setId(1);
Book b = BookByChoose(book);
System.out.println(b);*/
}
}
如果运⾏之后控制台的进度条是绿⾊就代表成功了,注意:有些表的id是⾃增长的话,SQL语句哪⾥id就要去掉,不然会报错*
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论