0%

MYBAITS1 第一个程序

1.安装maven

1
2
3
4
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>x.x.x</version></dependency>

注意:加一个logger 这个参考官方文档

2.创建一个实体类,和dao层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class类  student
private int id;
private String name;
private String grade;
dao层
studentDao层
insertStudent(Student student);
updateStudent(Student student);
delStudent(Student student);
selectStudent(int id); //只测试查询,此列子
dao层的xml
studentDao层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”>
<mapper namespace=“org.mybatis.example.studentDao“>
<select id=“selectStudent“ resultType=“student“>
select * from student where id = #{id}
</select>
</mapper>

配置mybaits.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?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=“${driver}”/>
<property name=“url” value=“${url}”/>
<property name=“username” value=“${username}”/>
<property name=“password” value=“${password}”/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource=“org/mybatis/example/studentMapper.xml”/>
</mappers>
</configuration>

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
@test
public void test(){
String resource = “org/mybatis/example/mybatis-config.xml”;
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession session = sqlSessionFactory.openSession();
try {
student student= session.selectStudent(1);
syso(student);
} finally {
session.close();
}
}