MyBatis入门示例――MyBatis学习笔记之一 (二)

2014-11-24 08:26:41 · 作者: · 浏览: 1
me) {
21. this.name = name;
22. }
23. public String getGender() {
24. return gender;
25. }
26. public void setGender(String gender) {
27. this.gender = gender;
28. }
29. public String getMajor() {
30. return major;
31. }
32. public void setMajor(String major) {
33. this.major = major;
34. }
35. public String getGrade() {
36. return grade;
37. }
38. public void setGrade(String grade) {
39. this.grade = grade;
40. }
41.
42. }

按照包的层次结构,在src目录下建立子目录层次com\abc\domain,然后把Student.java存放于此。
MyBatis需要我们提供一个接口,在接口中声明访问数据库的方法。因此,编写接口StudentMapper.java如下:

1. package com.abc.mapper;
2.
3. import com.abc.domain.Student;
4.
5. public interface StudentMapper {
6.
7. //根据学生ID查询学生实体
8. public Student getById(int id);
9.
10. }

类似地,将此文件放置在src目录下的com\abc\mapper目录下。
现在编写上面提到的mapper文件StudentMapper.xml。在此文件里,我们写好查询的SQL语句,并配置好映射关系。内容如下:
1. < xml version="1.0" encoding="UTF-8" >
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.

16.
17.
18. 方法名和参数类型。SQL语句中以“#{}”的形式引用参数-->
19.
23.
24.

MyBatis将根据此文件帮我们实现StudentMapper接口。下面编写TestMyBatis.java,实现我们的功能。代码如下:
1. package com.test;
2.
3. import java.io.IOException;
4. import java.io.Reader;
5. import org.apache.ibatis.io.Resources;
6. import org.apache.ibatis.session.SqlSessionFactory;
7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
8. import org.apache.ibatis.session.SqlSession;
9. import org.apache.ibatis.session.SqlSessionFactory;
10. import com.abc.mapper.StudentMapper;
11. import com.abc.domain.Student;
12.
13.
14. public class TestMyBatis
15. {
16. public static void main(String[] args)
17. {
18. //与configuration.xml中的mapper配置类似,告诉MyBatis
19. //应读取的核心配置文件
20. String resource = "resources/configuration.xml";
21. Reader reader = null;
22. try{
23. reader = Resources.getResourceAsReader(resource);
24. }catch(IOException e)
25. {
26. e.printStackTrace();
27. }
28.
29. //创建SqlSessionFactory实例。没有指定要用到的
30. //environment,则使用默认的environment
31. SqlSessionFactory sqlSessionFactory
32. = new SqlSessionFactoryBuilder().build(reader);
33.
34. SqlSession sqlSession = sqlSessionFactory.openSession();
35.
36. try{
37. StudentMapper mapper =
38. sqlSession.getMapper(StudentMapper.class);
39. Student student = mapper.getById(1);
40.
41. if(student != null)
42. {
43. System.out.println("姓名: "+student.getName()
44. +"\n专业: "+student.getMajor());
45. }
46. else
47. {
48. Syste