1.环境搭建
导入jar包,其中mybatis3.2.7是核心,connector是驱动,其他ja包是mybatis的依赖
2.准备主配置文件SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- mybatis和spring整合过后废除 -->
<environments default="development">
<environment id="development">
<!-- 和jdbc的事物管理 -->
<transactionManager type="JDBC" />
<!-- 数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/community?useSSL=false" />
<property name="username" value="root" />
<property name="password" value="1234" />
</dataSource>
</environment>
</environments>
</configuration>
3.实现根据id查询用户信息
3.1 编写与数据库中表对应的实体类,且要有无参构造器
3.2 编写实体类的映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!-- 命名空间,用于隔离sql,后面还有一个很重要的作用 -->
<mapper namespace="test">
<!--id是sql的唯一标记,在同一namespace中唯一-->
<!--parameterType代表输入参数的类型-->
<!--resultType指定sql执行后的结果集参数,当有多条结果时会自动生成对应的List集合中-->
<select id="findUserById" parameterType="long" resultType="day04Mybatis.pojo.User">
select * from gxa_user where id=#{arg0}
</select>
</mapper>
4.主配置文件SqlMapConfig.xml中加载映射文件
<!--加载映射文件-->
<mappers>
<mapper resource="User.xml"></mapper>
</mappers>
5.编写java代码测试
public class MybatisTest {
public static void main(String[] args) throws IOException {
//1.创建SqlSessionFactoryBuilder对象
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//2.读取xml文件
InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
//3.读取文件内容构建SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(in);
//4.获得SqlSession对象
SqlSession session = sqlSessionFactory.openSession();
//5.执行sql并返回结果
//第一个参数为sql的id
//第二个参数为传入的查询条件
User user = session.selectOne("findUserById",1L);
System.out.println(user);
}
}
6.根据用户名模糊查询方式一(查询条件需要传入%)
6.1 编写映射文件
<select id="findUserByUsername1" parameterType="string" resultType="day04Mybatis.pojo.User">
<!--mybatis在底层处理#时会进行预编译,所以会自动在#前后加上引号,可以防止sql注入-->
select * from gxa_user where username like #{arg0}
</select>
6.2 编写测试代码
List<User> users = session.selectList("findUserByUsername1","%强%");
7.根据用户名模糊查询方式二(可能会导致sql注入)
7.1 编写映射文件
<select id="findUserByUsername2" parameterType="string" resultType="day04Mybatis.pojo.User">
select * from gxa_user where username like '%${value}%'
</select>
7.2 编写测试代码
List<User> users = session.selectList("findUserByUsername2","强");
System.out.println(users.size());
8.根据用户名模糊查询方式三,推荐使用
8.1 编写映射文件
<select id="findUserByUsername3" parameterType="string" resultType="day04Mybatis.pojo.User">
<!--使用concat会进行字符串拼接-->
select * from gxa_user where username like concat("%",#{arg0},"%")
</select>
8.2 编写测试代码
List<User> users = session.selectList("findUserByUsername3","强");
System.out.println(users.size());