编写第一个Mybatis
创建数据库
CREATE DATABASE mybatis;
USE mybatis;
CREATE TABLE USER ( id INT NOT NULL PRIMARY KEY,
NAME VARCHAR(64) NOT NULL,
pwd VARCHAR(64) NOT NULL )
ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO USER (id,NAME,pwd)VALUE (1,'张三','123123');
INSERT INTO USER (id,NAME,pwd)VALUES (2,'小落','12341234'),(3,'李四','1231233');
创建项目
1.创建一个普通的Maven项目
2.删除src目录,形成父工程
3.导入需要的包
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
4.编辑包的结构
5.编写Mybatis.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>
<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:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8"/><!--连接数据库-->
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<!--每一个Mapper.xml都需要在Mybatis的核心配置文件中注册-->
<mappers>
<mapper resource="com/Google/Dao/userMapper.xml"></mapper>
</mappers>
</configuration>
5.1报错
### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 449 milliseconds ago. The last packet sent successfully to the server was 442 milliseconds ago.
这里的问题出在数据库,所以检查数据库连接。发现useSSL=true
要改为useSSL=false;
6.编写工具类(getSession)
package com.Google.units;
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 sqlSessionFactory {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
String resource = "Mybatis.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
/*sqlsession完全包含了所有面向数据库执行sql语句的所有方法*/
public static SqlSession getsqlSession(){
return sqlSessionFactory.openSession();
}
}
7.编写实体类
package com.Google.pojo;
public class User {
private int id;
private String name;
private String pwd;
public User() {
}
public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}
8.编写接口
package com.Google.Dao;
import com.Google.pojo.User;
import java.util.List;
public interface userMapper {
/*定义一个获取user数据的接口*/
List<User> getUserList();
}
9.编写Mapper.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">
<!--namespace 用于绑定一个对应的Mapper接口-->
<mapper namespace="com.Google.Dao.userMapper">
<!--id: 写接口中的方法-->
<!--resultType: (返回结果的数据类型),这里要填写具体的实体类-->
<select id="getUserList" resultType="com.Google.pojo.User">
select * from user
</select>
</mapper>
10测试
package com.Google.Dao;
import com.Google.pojo.User;
import com.Google.units.sqlSessionFactory;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.List;
public class userDao {
@Test
public void test() throws Exception{
SqlSession sqlSession = sqlSessionFactory.getsqlSession();
userMapper md =sqlSession.getMapper(userMapper.class);
List<User> userList = md.getUserList();
for (User user : userList) {
System.out.println(user);
}
}
}
注意点
1.先把需要配置的再区写测试,防止测试类的名字和Dao一样,这样先写测试类,然后再去配置文件,可能会把测试类配置到Mybatis配置文件中,这样就会报这样的错
type class com.google.dao.usermapper is not known to the mapperregistry.
2.由于Maven中约定大于配置,所以我们配置的文件可能会被过滤掉,只需要加入这些代码,就可解决这样的问题
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
3.最常见的错误
org.apache.ibatis.binding.BindingException: Type interface com.Google.Dao.userMapper is not known to the MapperRegistry.
这里就是要在Mybatis.xml和Dao目录下的配置文件一起配置,具体如下
<!--每一个Mapper.xml都需要在Mybatis的核心配置文件中注册-->
<mappers>
<mapper resource="com/Google/Dao/userMapper.xml"></mapper>
</mappers>
<!--namespace 用于绑定一个对应的Mapper接口-->
<mapper namespace="com.Google.Dao.userMapper">
<!--id: 写接口中的方法-->
<!--resultType: (返回结果的数据类型),这里要填写具体的实体类-->
<select id="getUserList" resultType="com.Google.pojo.User">
select * from user
</select>
</mapper>