插入过程
接口
int insertShop(Shop shop); |
映射
<insert id="insertShop" parameterType="Shop" useGeneratedKeys="true" keyProperty="id"> INSERT INTO `oto`.`tb_shop` ( `owner_id`, `area_id`, `shop_category_id`, `shop_name`, `shop_desc`, `shop_addr`, `phone`, `shop_img`, `priority`, `advice` ) VALUES ( #{ownerId}, #{areaId}, #{categoryId}, #{name}, #{desc}, #{addr}, #{phone}, #{image}, #{priority}, #{advice} ) ;</insert> |
测试
@Testpublic void testInsertShop() { String template = "查询结果: %s"; SqlSession session = MyBatisUtil.getSqlSession(); ShopMapper mapper = session.getMapper(ShopMapper.class); Shop shop = new Shop(); shop.setOwnerId(1); shop.setName("Hello Jack"); mapper.insertShop(shop); session.commit(); session.close(); System.out.printf(template, shop);} |
结果
Opening JDBC Connection Created connection 118555812. Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@71104a4] ==> Preparing: INSERT INTO `oto`.`tb_shop` ( `owner_id`, `area_id`, `shop_category_id`, `shop_name`, `shop_desc`, `shop_addr`, `phone`, `shop_img`, `priority`, `advice` ) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ? ) ; ==> Parameters: 1(Integer), null, null, Hello Jack(String), null, null, null, null, null, null <== Updates: 1 Committing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@71104a4] Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@71104a4] Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@71104a4] Returned connection 118555812 to pool. 查询结果: Shop{id=41, ownerId=1, areaId=null, categoryId=null, name=‘Hello Jack‘, desc=‘null‘, addr=‘null‘, phone=‘null‘, image=‘null‘, priority=null, createTime=null, lastEditTime=null, enableStatus=null, advice=‘null‘} |
第一种方法: 在insert语句标签中指明pojo对象中对应的id
<insert id="insertShop" parameterType="Shop" useGeneratedKeys="true" keyProperty="id"> |
第二种方法: 全局配置
在mybatis-config.xml文件中进行配置
<setting name="userGeneratedKeys" value="true" /> |
在mapper里面仅设置keyProperty
第三种方法: 不支持自增的数据库比如说Oracle
没有学过Oracle,等女朋友来教我
原文地址:https://www.cnblogs.com/litran/p/10543837.html
时间: 2024-11-02 13:30:29