一、设置paramterType
1.类型为基本类型
a.代码示例
映射文件:
<select id="findShopCartInfoById" parameterType="int" resultType="ShopCart"> select* from shopcart where shopcartid = #{id} </select>
Mapper接口:
ShopCart findShopCartInfoById(int id);
测试代码:
ShopCartMapper scm = sqlSession.getMapper(ShopCartMapper.class); ShopCart shopCart = scm.findShopCartInfoById(14);
2.类型为对象类
映射文件:
<insert id="addShopCartInfo" parameterType="ShopCart"> insert into shopcart(buyerid,bookid,amount,price,status) values(#{buyerId},#{bookId},#{amount},#{price},#{status}) </insert>
Mapper接口:
int addShopCartInfo(ShopCart shopCart);
ShopCart.java
package com.yh.entity; public class ShopCart { private int shopCartId; private int buyerId; private int bookId; private short amount; private float price; private short status; private Book book; public ShopCart() { } public ShopCart(int buyerId, int bookId, int amount, int price, int status) { this.buyerId = buyerId; this.bookId = bookId; this.amount = (short) amount; this.price = price; this.status = (short) status; } public int getBuyerId() { return buyerId; } public void setBuyerId(int buyerId) { this.buyerId = buyerId; } public int getBookId() { return bookId; } public void setBookId(int bookId) { this.bookId = bookId; } public short getAmount() { return amount; } public void setAmount(short amount) { this.amount = amount; } public float getPrice() { return price; } public void setPrice(float price) { this.price = price; } public short getStatus() { return status; } public void setStatus(short status) { this.status = status; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } public int getShopCartId() { return shopCartId; } public void setShopCartId(int shopCartId) { this.shopCartId = shopCartId; } }
测试代码:
@ResponseBody @RequestMapping(value = "/addInfo", produces = "application/json; charset=utf-8", method = RequestMethod.GET) public String addInfo(HttpSession session, ShopCart shopCart) { this.init(); shopCart.setBuyerId((int) session.getAttribute("userId")); ShopCartMapper scm = sqlSession.getMapper(ShopCartMapper.class);int result = scm.addShopCartInfo(shopCart); this.destroy(); return result != 0 ? "添加成功" : "添加失败"; }
二、注解Mapper接口中方法参数
设置Mapper接口中@Param注释的值和映射文件中sql语句中的“参数名”相同。
映射文件:
<update id="changeAmount"> update shopcart set amount=#{amount} where shopcartid = #{shopCartId} </update>
Mapper接口:
int changeAmount(@Param("amount") int amount, @Param("shopCartId") int shopCartId);
测试代码:
@ResponseBody @RequestMapping(value = "/changeAmount", produces = "application/json;charset=utf-8") public String changeAmount(@RequestParam(value = "amount") String amount, @RequestParam(value = "shopCartId") String shopCartId) { this.init(); ShopCartMapper scm = sqlSession.getMapper(ShopCartMapper.class); int result = scm.changeAmount(Integer.valueOf(amount), Integer.valueOf(shopCartId)); this.destroy(); return result != 0 ? "修改成功" : "修改失败"; }