下载源码
到github下载mybatis3就可以了
创建数据库和表格
数据库名字为 test_db
表创建语句,及插入数据:
1 | CREATE TABLE STUDENTS ( |
配置
用intellij idea或其他别的ide打开mybatis项目
pom.xml增加配置
在mybatis的pom.xml配置中增加以下配置:1
2
3
4
5
6<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.22</version>
<scope>runtime</scope>
</dependency>
resource配置
在test目录下增加resource文件夹,并设置为test resource。
在文件夹下创建mybatis配置文件 mybatis-config.xml:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22<?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>
<typeAliases>
<typeAlias alias="Student" type="cn.zhengjianglong.sshdemo.entity.Student" />
</typeAliases>
<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/test_db" />
<property name="username" value="root" />
<property name="password" value="admin" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/StudentMapper.xml" />
</mappers>
</configuration>
在resource文件夹下创建文件夹mapper,并在mapper下新建StudentMapper.xml1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22<?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="cn.zhengjianglong.sshdemo.entity.mapper.StudentMapper">
<resultMap type="Student" id="StudentResult">
<id property="studId" column="stud_id"/>
<result property="name" column="name"/>
<result property="email" column="email"/>
<result property="dob" column="dob"/>
</resultMap>
<select id="findAllStudents" resultMap="StudentResult">
SELECT * FROM STUDENTS
</select>
<select id="findStudentById" parameterType="int" resultType="Student">
SELECT STUD_ID AS STUDID, NAME, EMAIL, DOB
FROM STUDENTS WHERE STUD_ID=#{Id}
</select>
<insert id="insertStudent" parameterType="Student">
INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB)
VALUES(#{studId },#{name},#{email},#{dob})
</insert>
</mapper>
创建测试类
Student
1 | package cn.zhengjianglong.sshdemo.entity; |
StudentMapper
1 | package cn.zhengjianglong.sshdemo.entity.mapper; |
MyBatisSqlSessionFactory
1 | public class MyBatisSqlSessionFactory { |
StudentService
1 | public class StudentService { |
StudentServiceTest
1 | public class StudentServiceTest { |
参考
- [1] ashan博客-mybatis系列
- [2] 《Java Persistence with MyBatis 3》