040_Mybatis注解开发
作者:互联网
目录
使用注解开发
mybatis-config.xml中注册接口
<mappers>
<!--绑定接口-->
<mapper class="com.qing.dao.UserMapper"/>
</mappers>
Mapper接口中添加注解
package com.qing.dao;
import com.qing.pojo.User;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
import java.util.Map;
/**
* 接口
*/
public interface UserMapper {
/**
* 查询全部用户
*
* @return
*/
@Select("select * from mybatis.user")
List<User> getUserList();
/**
* 根据ID查询用户
*
* @param id
* @return
*/
@Select("select * from mybatis.user where id=#{userId} ")
User getUserById(@Param("userId") int id);
/**
* 新增用户
*
* @param user
* @return
*/
@Insert("insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd})")
int insert(User user);
}
测试
package com.qing.dao;
import com.qing.pojo.User;
import com.qing.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class UserMapperTest {
/**
* 查询全部用户
*/
@Test
public void getUserList() {
SqlSession sqlSession = null;
try {
// 获取sqlSession
sqlSession = MybatisUtils.getSqlSession();
// 执行SQL
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
List<User> userList = mapper.getUserList();
for (User user : userList) {
System.out.println(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭sqlSession
sqlSession.close();
}
}
/**
* 根据ID查询用户
*/
@Test
public void getUserById() {
SqlSession sqlSession = null;
try {
// 获取sqlSession
sqlSession = MybatisUtils.getSqlSession();
// 执行SQL
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user = mapper.getUserById(1);
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭sqlSession
sqlSession.close();
}
}
}
sqlSession设置自动提交
/**
* 获取 SqlSession
* @return
*/
public static SqlSession getSqlSession() {
SqlSession sqlSession = sqlSessionFactory.openSession(true);
return sqlSession;
}
@Param()注解
- 基本类型的参数或者String类型的参数,需要加上
- 引用类型不需要加
- 如果只有一个基本类型的参数,可以不加,但建议也加上
- Mapper中的引用就是@Param()中设定的属性名
标签:SqlSession,User,sqlSession,user,import,Mybatis,注解,040 来源: https://www.cnblogs.com/wl3pb/p/14999220.html