IDEA搭建mybatis框架的maven项目
搭建环境
jdk 1.8
Tomcat 7.0
maven 3.6.1
idea 2019
第一步先建一个项目
maven项目就搭建好了
下一步搭建mybatis框架,打开pom.xml文件,输入以下代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>Test</groupId>
<artifactId>test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.29</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project>
创建student类
package com.test.pojo;
public class Student {
private Integer id;
private String sname;
private String spwd;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSpwd() {
return spwd;
}
public void setSpwd(String spwd) {
this.spwd = spwd;
}
}
在main文件夹下创建resources文件夹
创建student类的mapper文件
resources下右键
```java
<?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指定Dao接口的完整类名
mybatis会依据这个接口动态创建一个实现类去实现这个接口, 而这个实现类是一个Mapper对象
-->
<mapper namespace="com.test.dao.StudentDao">
<!--id ="接口中的方法名" parameterType="传入的参数类型" resultType = "返回实体类对象,使用包.类名"-->
<select id="findById" parameterType="int" resultType="com.test.pojo.Student">
select * from tb_student where id = #{id}
</select>
</mapper>
在java文件夹下创建dao层接口 编写测试类
public interface StudentDao {
public List<Student> findById(int id);
}
public class StudentTest {
@Test
public void StudentFindByIdTest(){
String resources = "mybatis-config.xml";
Reader reader=null;
try {
reader= Resources.getResourceAsReader(resources);
} catch (IOException e) {
e.printStackTrace();
}
//初始化mybatis,创建SqlSessionFactory类的实例
SqlSessionFactory sqlMapper=new SqlSessionFactoryBuilder().build(reader);
SqlSession session=sqlMapper.openSession();
StudentDao StudentMapper=session.getMapper(StudentDao.class);
List<Student> list=StudentMapper.findById(1);
System.out.println(list);
session.close();
}
}
idea搭建mybatis框架完成