赞
踩
在mybatis中注解开发没有xml方便,用的不是很多,但是在其它框架中注解开发是用的很多的
1、注解在接口上实现
- //根据姓名查找用户
- @Select("select * from mybatis1.user where id = #{id}")
- User getUserId(int id);
2、注解开发是在核心配置文件中绑定接口,而不是mapper.xml文件
- <!--Mybatis注解开发时需要绑定接口-->
- <mappers>
- <mapper class="com.li.dao.UserMapper"/>
- </mappers>
3、测试
- //根据id查询
- @Test
- public void test1(){
- SqlSession sqlSession = MybatisUtils.getSqlSession();
-
- UserMapper mapper = sqlSession.getMapper(UserMapper.class);
-
- User user = mapper.getUserId(1);
- System.out.println(user);
-
- sqlSession.close();
-
- }
增删改
抽象类:
参数有多个且是基本数据类型时、Sting类型时、
一定要在前面加上@Param("属性名")
引用数据类型可以不加,只有一个基本数据类型可以不加,建议都加上
因为我们在sql中引用的就是我们@Param("属性名")的属性名
-
- //新增一个用户
- @Insert("insert into mybatis1.user values (#{id},#{name},#{password})")
- int insertUser(User user);
-
- //删除一个用户
- @Delete("delete from mybatis1.user where id =10 ")
- int deleteUser(int id);
-
- //修改用户数据
- @Update("update mybatis1.user set name=#{name} where id =#{id};")
- int updateUser(User user);
-
- //查询全部用户的方法
- @Select("select * from mybatis1.user")
- List<User> getUserList();
-
- //根据姓名查找用户
- //参数有多个且是基本数据类型时一定要在前面加上@Param("参数名")
- @Select("select * from mybatis1.user where id = #{id} and name = #{name}")
- User getUserId(@Param("id") int id,@Param("name") String name);
测试类:
- //查
- @Test
- public void test1(){
- SqlSession sqlSession = MybatisUtils.getSqlSession();
-
- UserMapper mapper = sqlSession.getMapper(UserMapper.class);
-
- User userId = mapper.getUserId(1,"帅哥");
-
- System.out.println(userId);
-
- sqlSession.close();
-
- }
- //增
- @Test
- public void test2(){
- SqlSession sqlSession = MybatisUtils.getSqlSession();
-
- UserMapper mapper = sqlSession.getMapper(UserMapper.class);
-
- int in = mapper.insertUser(new User(10, "vvf", "123"));
- if(in > 0){
- sqlSession.commit();
- System.out.println("添加成功");
- }
-
- sqlSession.close();
-
- }
- //删
- @Test
- public void test3(){
- SqlSession sqlSession = MybatisUtils.getSqlSession();
-
- UserMapper mapper = sqlSession.getMapper(UserMapper.class);
-
- int in = mapper.deleteUser(10);
-
- if(in > 0){
- sqlSession.commit(); //提交事务
- System.out.println("删除成功");
- }
-
- sqlSession.close();
-
- }
- //改
- @Test
- public void test4(){
- SqlSession sqlSession = MybatisUtils.getSqlSession();
-
- UserMapper mapper = sqlSession.getMapper(UserMapper.class);
-
- int in = mapper.updateUser(new User(9, "大帅哥", "nn"));
-
- if(in > 0){
- sqlSession.commit(); //提交事务
- System.out.println("修改成功");
- }
-
- sqlSession.close();
-
- }
上面我们都是手动提交事务的,我们可以设置自动提交事务
- //获取SqlSession
- public static SqlSession getSqlSession(){
- //在这里设置一个true就把事务自动提交打开了
- return sqlSessionFactory.openSession(true);
- }
openSession方法的重载有支持自动提交事务的实现
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。