温馨提示×

mybatis如何向数据库添加数据

小亿
175
2024-04-12 10:23:47
栏目: 大数据
亿速云云数据库,读写分离,安全稳定,弹性扩容,低至0.3元/天!! 点击查看>>

要向数据库添加数据,可以通过MyBatis使用插入语句来实现。以下是一个简单的示例:

  1. 在MyBatis的Mapper接口中定义一个插入方法:
public interface UserMapper {
    void insertUser(User user);
}
  1. 在Mapper XML文件中编写对应的插入语句:
<insert id="insertUser" parameterType="com.example.User">
    INSERT INTO user (id, username, password) VALUES (#{id}, #{username}, #{password})
</insert>
  1. 在Java代码中调用Mapper接口的插入方法:
User user = new User();
user.setId(1);
user.setUsername("john");
user.setPassword("123456");

SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

userMapper.insertUser(user);

sqlSession.commit();
sqlSession.close();

通过以上步骤,就可以向数据库中添加数据并提交事务。

亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>

推荐阅读:mybatis怎么向数据库添加数据

0