新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

mybatis的insert语句如何使用,mybatis的insert语句返回值

发布时间:2023-09-27 14:26:37

mybatis的insert语句如何使用

MyBatis 的 insert 语句可以通过 XML 配置文件还是注解方式进行使用。

  1. XML 配置文件方式:

在 Mapper XML 文件中,使用 标签定义 insert 语句。示例:


INSERT INTO user (id, name, age)
VALUES (#{id}, #{name}, #{age})

在 Java 代码中调用 insert 语句:

User user = new User();
user.setId(1);
user.setName("John");
user.setAge(25);
session.insert("insertUser", user);
  1. 注解方式:

在 Mapper 接口中使用 @Insert 注解定义 insert 语句。示例:

@Insert("INSERT INTO user (id, name, age) VALUES (#{id}, #{name}, #{age})")
void insertUser(User user);

在 Java 代码中调用 insert 语句:

User user = new User();
user.setId(1);
user.setName("John");
user.setAge(25);
mapper.insertUser(user);

注意:

  • 插入语句中的参数可使用 #{} 占位符进行援用。
  • 对自动生成的主键,可使用 useGeneratedKeys="true" 配置来获得生成的主键值。