使用mybatis ORM框架进行数据的插入操作
先假设数据库中有一个user表,其具体信息如下:

1.使用MySQL作为连接数据库时
一条数据插入时的方式
点击查看代码
| |
| <insert id="insertUser" useGeneratedKeys="true" keyProperty="id"> |
| insert into user_demo(id,user_name,password,email,age,sex) |
| values(#{id},#{userName},#{password},#{email},#{age},#{sex}) |
| </insert> |
| |
| |
| <sql id="insert_prefix"> |
| <trim prefix="(" suffix=")" suffixOverrides=","> |
| <if test="id != null"> |
| id, |
| </if> |
| <if test="userName != null and userName !=''"> |
| user_name, |
| </if> |
| <if test="password != null and password !=''"> |
| password, |
| </if> |
| <if test="email != null and email !=''"> |
| email, |
| </if> |
| <if test="age != null"> |
| age, |
| </if> |
| <if test="sex != null and sex !=''"> |
| sex, |
| </if> |
| <if test="deptId != null"> |
| dept_id, |
| </if> |
| </trim> |
| </sql> |
| |
| <sql id="insert_suffix"> |
| <trim prefix="(" suffix=")" suffixOverrides=","> |
| <if test="id != null"> |
| #{id}, |
| </if> |
| <if test="userName != null and userName !=''"> |
| #{userName}, |
| </if> |
| <if test="password != null and password !=''"> |
| #{password}, |
| </if> |
| <if test="email != null and email !=''"> |
| #{email}, |
| </if> |
| <if test="age != null"> |
| #{age}, |
| </if> |
| <if test="sex != null and sex !=''"> |
| #{sex}, |
| </if> |
| <if test="deptId != null"> |
| #{deptId}, |
| </if> |
| </trim> |
| </sql> |
| <insert id="insertUserSelect" useGeneratedKeys="true" keyProperty="id"> |
| insert into user_demo |
| <include refid="insert_prefix"/> |
| values |
| <include refid="insert_suffix"/> |
| </insert> |
| |
批量插入数据
点击查看代码
| <insert id="insertBatchUser" useGeneratedKeys="true" keyProperty="id"> |
| insert into user_demo(id,user_name,password,email,age,sex) |
| values |
| <foreach collection="list" item="item" open="(" separator="," close=")"> |
| #{item.id},#{item.userName},#{item.password},#{item.email},#{item.age},#{item.sex} |
| </foreach> |
| </insert> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!