Mapper.xml中
自动生成key id值方法一
<!--这里配置了自动生成key 以及配置id重设置到对象中-->
<insert id="insertAnimalByList" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
insert into animal(`type`,age_max , update_time) values
<!--注意这里collection对应的键值,使用的是list的默认值-->
<foreach collection="list" item="animal" separator=",">
(#{animal.type},#{animal.ageMax},#{animal.updateTime})
</foreach>
</insert>
java方法使用
private static void insertDatas() throws IOException {
PropertyConfigurator.configure("src/main/resources/mappings3/log4j.properties");
InputStream inputStream=Resources.getResourceAsStream("mappings3/mybatis-config.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
try (SqlSession sqlSession=sqlSessionFactory.openSession()){
ArrayList<Animal> animals=new ArrayList<>();
animals.add(new Animal("豹子","15",new Date()));
animals.add(new Animal("蝴蝶","1",new Date()));
animals.add(new Animal("咕咕咕","12",new Date()));
/*AnimalVO animalVO=new AnimalVO();
animalVO.setAnimals(animals);*/
sqlSession.insert("com.ly3.entity.AnimalMapper.insertAnimalByList",animals);
sqlSession.commit();
}
}
自动生成key id值方法二
单条数据新增
<insert id="insertAnimal2" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
<selectKey keyProperty="id" resultType="int" order="AFTER">
SELECT LAST_INSERT_ID()
</selectKey>
insert into animal(id,`type`,age_max,update_time) values(#{id},#{type},#{ageMax},#{updateTime})
</insert>
网友评论