项目中遇到,记录一下。
Entity
public class Student{
private Integer id;
private String name;
private Intger age ;
private double salary;
}
Service
@Service
public class Save implements ISave{
@Autowired
private Mapper mapper;
@Override
public void save(List<Student> list) {
mapper.save(list);
for(int i = 0; i<list.size();i++){
System.out.println(list.get(i).getId());
}
}
}
这里打印结果就是刚才插入的数据返回的主键,XML会根据keyProperty属性的值把主键放到所对应的字段里
Mapper
@Mapper
public interface Mapper {
void save(@Param("list")List<Student> list);//正常调用就可以
}
XML
<insert id="save" parameterType="java.util.List"
useGeneratedKeys="true" keyProperty="id">
INSERT INTO
student_table
(
name,
age,
salary
)
VALUES
<foreach collection="list" item="item" index="index" separator=",">
(
#{item.name},
#{item.age},
#{item.salary}
)
</foreach>
</insert>
注意两个属性:
useGeneratedKeys="true" //是否返回主键
keyProperty="id" //实体类中接收主键的字段