在MyBatis中使用注解实现增删改查

在Mybatis.xml中配置

<!--注册接口-->
<mappers>
<mapper class="com.Google.Dao.userMapper"/>
</mappers>

//增加
@Insert("insert into user (id,name,pwd) values (#{id},#{name},#{pwd})")
int insert(@Param("id") int id,@Param("name") String name,@Param("pwd") String Password);
```java
public void insert (){
SqlSession sqlSession = sqlSessionFactory.getsqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
int i = mapper.insert(5, "xixi","23234234");
if(i>0){
sqlSession.commit();
}
sqlSession.close();
}

//删除
@Delete("delete from user where id = #{id}")
int Delete (int id);
@Test
public void Delete (){
SqlSession sqlSession = sqlSessionFactory.getsqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
int i = mapper.Delete(1);
if(i>0){
sqlSession.commit();
}
sqlSession.close();
}

//修改
@Update("update user set name=#{name} where id=#{id}")
int update (@Param("name") String name,@Param("id") int id);
@Test
public void update (){
SqlSession sqlSession = sqlSessionFactory.getsqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
int i = mapper.update("haha", 1);
if(i>0){
sqlSession.commit();
}
sqlSession.close();
}

//查询
@Select("select * from user where id=#{id}")
User getUserByID1(@Param("id") int id);
public void getUserByID(){
SqlSession sqlSession = sqlSessionFactory.getsqlSession();
userMapper mapper = sqlSession.getMapper(userMapper.class);
User user = mapper.getUserByID1(2);
System.out.println(user);
sqlSession.close();
}
posted @   小罗要有出息  阅读(114)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示