1.引入依赖(pom.xml)
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency>
2.全局配置文件(mybatis-config.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> <properties> <property name="driver" value="com.mysql.jdbc.Driver"/> <property name="url" value="jdbc:mysql://127.0.0.1:3306/ssmdemo?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true"/>
<property name="username" value="root"/> <property name="password" value="123456"/> </properties> <!-- 环境,可以配置多个,default:指定采用哪个环境 --> <environments default="test"> <!-- id:唯一标识 --> <environment id="test"> <!-- 事务管理器,JDBC类型的事务管理器 --> <transactionManager type="JDBC" /> <!-- 数据源,池类型的数据源 --> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://127.0.0.1:3306/ssmdemo"/>
<property name="username" value="root" /> <property name="password" value="123456" /> </dataSource> </environment> <environment id="development"> <!-- 事务管理器,JDBC类型的事务管理器 --> <transactionManager type="JDBC" /> <!-- 数据源,池类型的数据源 --> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <!-- 配置了properties,所以可以直接引用 --> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </dataSource> </environment> </environments> </configuration>
3.配置Map.xml(MyMapper.xml)
<?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"> <!-- mapper:根标签,namespace:命名空间,随便写,一般保证命名空间唯一 --> <mapper namespace="MyMapper"> <!-- statement,内容:sql语句。id:唯一标识,随便写,在同一个命名空间下保持唯一 resultType:sql语句查询结果集的封装类型,tb_user即为数据库中的表 --> <select id="selectUser" resultType="com.zpc.mybatis.User"> select * from tb_user where id = #{id} </select> </mapper>
4.修改全局配置文件(mybatis-config.xml)
配上MyMapper.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> <mappers> <mapper resource="mappers/MyMapper.xml" /> </mappers> </configuration>
5.构建sqlSessionFactory(MybatisTest.java)
// 指定全局配置文件 String resource = "mybatis-config.xml"; // 读取配置文件 InputStream inputStream = Resources.getResourceAsStream(resource); // 构建sqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
6.打开sqlSession会话,并执行sql(MybatisTest.java)
// 获取sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); // 操作CRUD,第一个参数:指定statement,规则:命名空间+“.”+statementId // 第二个参数:指定传入sql的参数:这里是用户id User user = sqlSession.selectOne("MyMapper.selectUser", 1); System.out.println(user);
完整代码:MybatisTest.java
import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; public class MybatisTest { public static void main(String[] args) throws Exception { // 指定全局配置文件 String resource = "mybatis-config.xml"; // 读取配置文件 InputStream inputStream = Resources.getResourceAsStream(resource); // 构建sqlSessionFactory SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); // 获取sqlSession SqlSession sqlSession = sqlSessionFactory.openSession(); try { // 操作CRUD,第一个参数:指定statement,规则:命名空间+“.”+statementId // 第二个参数:指定传入sql的参数:这里是用户id User user = sqlSession.selectOne("MyMapper.selectUser", 1); System.out.println(user); } finally { sqlSession.close(); } } }
User.java
import lombok.Data; import java.util.Date; @Data public class User { private String id; private String userName; private String password; private String name; private Integer age; private Integer sex; private Date birthday; private String created; private String updated; }
7.目录结构
8.MyBatis使用步骤总结
1)配置mybatis-config.xml 全局的配置文件 (1、数据源,2、外部的mapper)
2)创建SqlSessionFactory
3)通过SqlSessionFactory创建SqlSession对象
4)通过SqlSession操作数据库 CRUD
5)调用session.commit()提交事务
6)调用session.close()关闭会话
9.解决数据库字段名和实体类属性名不一致的问题
查询数据的时候,发现查不到userName的信息:
User(id=1, userName=null, password=123456, name=鹏程, age=22, sex=1, birthday=Sun Sep 02 00:00:00 CDT 1990, created=2020-04-19 11:14:40.0, updated=2020-04-19 11:14:40.0)
原因:数据库的字段名是user_name,POJO中的属性名字是userName
两端不一致,造成mybatis无法填充对应的字段信息。修改方法:在sql语句中使用别名。
解决方案1:在sql语句中使用别名:
<select id="queryUserById" resultType="com.zpc.mybatis.pojo.User"> select tuser.id as id, tuser.user_name as userName, tuser.password as password, tuser.name as name, tuser.age as age, tuser.birthday as birthday, tuser.sex as sex, tuser.created as created, tuser.updated as updated from tb_user tuser where tuser.id = #{id}; </select>
解决方案2: 参考后面的resultMap –mapper具体的配置的时候
解决方案3:开启驼峰匹配,在mybatis-config.xml配置文件加入下面配置
#注意放置位置
<settings> <setting name="mapUnderscoreToCamelCase" value="true"/> </settings>