1.创建需要的student表,属性id,name
2.新建一个maven项目
(1)加入mybatis依赖,mysql驱动,junit,若显示报红则同步一下maven,maven会自动下载
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
(2)pom文件build中加入资源插件
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
3.创建student类的实体,包括getset构造方法以及toString方法。
4.创建studentdao接口,定义操作数据库的方法
public interface studentdao {
//查询一个学生
Student selectStudentbyid();
}
5.在与studentdao接口通包下创建studentdao.xml文件,写SQL语句,有增删改查语句各有不同的标签
<select id="selectStudentbyid" resultType="domain.Student">
select id,name,email,age from students where id=1;
</select>
6.创建mybatis的主配置文件在resources(只有一个)
(1)连接数据库
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/*?useUnicode=true&
characterEncoding=utf-8"/>
<property name="username" value="用户名"/>
<property name="password" value="密码"/>
(2)指定其他mapper文件位置
<mappers>
<mapper resource="从java开始studentdao.xml的路径"/>
</mappers>