第一个Mybatis程序
2.1搭建环境
2.2创建一个模块
2.3编写代码
- Dao层:UserMapper.java
package com.kuang.dao;
import com.kuang.pojo.User;
import java.util.List;
public interface UserMapper {
public List<User> getUserList();
}
- 接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件。
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.kuang.dao.UserMapper">
<select id="getUserList" resultType="com.kuang.pojo.User">
select * from mybatis.user
</select>
</mapper>
2.4测试
注意点:
org.apache.ibatis.binding.BindingException: Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.
MapperRegistry是什么?
核心配置文件中注册mappers
就是最外面那个pom.xml
Maven由于他的约定大于配置,我们之后可能会遇到我们写的配置文件,无法被导出或者生效的问题,解决方案:
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.yml</include>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
- junit测试
@Test
public void test(){
//第一步:获得sqlSession对象
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserDao userDao = sqlSession.getMapper(UserDao.class);
List<User> userList = userDao.getUserList();
for (User user : userList) {
System.out.println(user);
}
//关闭sqlSession
sqlSession.close();
}
mybatis程序步骤:
1,写mybatis-config.xml文件
2,写工具类MybatisUtils
3,写pojo下的User类
4,dao下的接口UserMapper和UserMapper.xml
出现的 一些问题:
1 字节的 UTF-8 序列的字节 1 无效。
解决办法:
把所有的配置文件即xml文件里面的UTF-8改成UTF8!
自己练习后的经验:
UserMapper.xml文件:
select语句中的id:就是对应的namespace中的方法名;
mybatis-config.xml文件:
UserMapperTest.java文件:
增删改一定要记得提交事务:sqlSession.commit();
模糊查询:
第一种:在Java代码中添加通配符
@Test
public void test(){
SqlSession sqlSession = MybatisUtils.getSqlSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
String selectlike = "%ang%";
List<User> users = mapper.selectLike(selectlike);
for (User user : users) {
System.out.println(user);
}
sqlSession.close();
}
第二种:在sql语句中拼接通配符,会引起SQL注入!