1、select选择
id是namespace中的方法。
1、写接口 User getUserById(int id);
2、写sql语句
<select id="getUserById" resultType="com.lin.pojo.User">
select * from mybatis.user where id=#{id};
</select>
3、写测试
@Test
public void getUserById(){
SqlSession sqlSession = Mybatis.getSqlSession();
Dao mapper = sqlSession.getMapper(Dao.class);
User userById = mapper.getUserById(1);
System.out.println(userById);
sqlSession.close();
}
4、工具类
public class Mybatis {
private static SqlSessionFactory sqlSessionFactory;
static {
try{
String resource = "mybatis.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
catch (Exception e){
e.printStackTrace();
}
}
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}
5、错误
mapper中要在mybatis的核心文件中注册
<mappers>
<mapper resource="com/lin/dao/Usermapper.xml"/>
</mappers>
6、map的运用
@Test
public void addUser(Map<String,Object> map){
SqlSession sqlSession = Mybatis.getSqlSession();
Dao mapper = sqlSession.getMapper(Dao.class);
HashMap<String, Object> map1 = new HashMap<String, Object>();
map1.put("userid","5");
map1.put("username","杨");
int i = mapper.addUser(map1);
System.out.println(i);
sqlSession.close();
}
7、情况说明
Map传递参数的时候,直接在sql中取出key即可 【parameterType="map“】
对象传递参数的时候,直接在sql中取对象的属性即可【parameterType=“object”】
只有一个基本类型的情况下,可以直接在sql取到
多个参数用map,或者用注解