MyBatis第一个程序

思路

搭建环境 --> 导入MyBatis --> 编写代码 --> 测试

代码演示

环境说明:

  • JDK 8
  • MySQL 5.7.19
  • maven-3.6.0
  • IDEA
1. 创建数据库并插入数据
CREATE DATABASE `mybatis`;

USE `mybatis`;

DROP TABLE IF EXISTS `user` (
	`id` int(10) AUTO_INCREMENT PRIMARY KEY,
    `name` varchar(30) DEFAULT NULL,
    `pwd` varchar(30) DEFAULT NULL
) ENGIN=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `user` (`name`,`pwd`) values ("linux","linux123") ("windows","windows123","macos","macos123");
2. 导入MyBatis相关jar包

可以去Maven Respository去搜索相关jar包。

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.4</version>
</dependency>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.19</version>
</dependency>
3. 编写配置文件
<?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>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:6379/mybatis?useSSL=true&amp;userUnicode=true&amp;characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="nihao2020"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="com/geek/dao/userMapper.xml"/>
  </mappers>
</configuration>
4. 编写MyBatis工具类
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.IOException;
import java.io.InputStream;

public class MyBatisUtils {
	private static SqlSessionFactory sqlSessionFactory;

	static {
		try {
			String resource = "mybatis-config.xml";
			InputStream inputStream = Resources.getResourceAsStream(resource);
			sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//获取SqlSession连接
	public static SqlSession getSession() {
		return sqlSessionFactory.openSession();
	}
}
5. 创建实体类
public class User {
    private int id;
    private String name;
    private String pwd;
    
    //有参构造器
    //无参构造器
    //set方法
    //get方法
    //toString重写
}

上面注释的部分自己写,或使用IDEA就能生成,在编辑区快捷键Alt + Insert,toString要重写,不然第8步打印会输出该对象的引用,格式为包名.类名.@八位字符

6. 编写Mapper接口类
import com.geek.pojo.User;
import java.util.List;

public interface UserMapper {
    List<User> selectUser();
}
7. 编写Mapper.xml配置文件

注意:namespace不要写错,否则会报错

<?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="com.geek.dao.UserMapper">
  <select id="selectUser" resultType="com.geek.pojo.User">
    select * from user
  </select>
</mapper>
8. 编写测试类

Junit包测试

public class MyTest {
    @Test
    public void selectUser() {
        SqlSession session = MybatisUtils.getSession();
        //方法一:
        //List<User> users = session.selectList("com.geek.mapper.UserMapper.selectUser");
        //方法二:
        UserMapper mapper = session.getMapper(UserMapper.class);
        List<User> users = mapper.selectUser();

        for (User user: users){
            System.out.println(user);
        }
        session.close();
    }
}
9. 运行测试

可能出现的问题

Maven静态资源过滤问题

<resources>
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>**/*.properties</include>
            <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
    </resource>
</resources>

第7步Mapper.xml中命名空间写错,可能会报类似这样的错误

Exception in thread "main" org.apache.ibatis.exceptions.PersistenceException:
### Error updating database. Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for xxdfly.mapping.userMaper.updateUser
### Cause: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for xxdfly.mapping.userMaper.updateUser
at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:26)
at org.apache.ibatis.session.defaults.DefaultSqlSession.update(DefaultSqlSession.java:154)
at test.MybatisTest.main(MybatisTest.java:37)
Caused by: java.lang.IllegalArgumentException: Mapped Statements collection does not contain value for xxdfly.mapping.userMaper.updateUser
posted @ 2020-03-04 21:26  Youpeng  阅读(177)  评论(0编辑  收藏  举报