查询语句是使用 MyBatis 时最常用的元素之一
select元素配置细节如下
属性
描述
取值
默认
id
在这个模式下唯一的标识符,可被其它语句引用
parameterType
传给此语句的参数的完整类名或别名
resultType
语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用)
resultMap
引用的外部resultMap 名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用)
flushCache
如果设为true,则会在每次语句调用的时候就会清空缓存。select 语句默认设为false
true|false
false
useCache
如果设为true,则语句的结果集将被缓存。select 语句默认设为false true|false false
timeout 设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定
true|false
false
timeout
设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定
正整数
未设置
fetchSize
设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定
正整数
驱动器决定
statementType
statement,preparedstatement,callablestatement。
预准备语句、可调用语句
STATEMENT
PREPARED
CALLABLE
PREPARED
resultSetType
forward_only,scroll_sensitive,scroll_insensitive
只转发,滚动敏感,不区分大小写的滚动
FORWARD_ONLY
SCROLL_SENSITIVE
SCROLL_INSENSITIVE
驱动器决定
例子:
1 <?xml version="1.0" encoding="UTF-8"?>
2 /p>
4 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
5
6
7 keyProperty="classId">
8 INSERT INTO users(username,PASSWORD)9 VALUES(#{username},#{password});10
11
12 resultMap="adminResultMap">
13 SELECT *FROM t_admin;14
15
16
17
18
19
20
21
28
29
下面是常用的增删查改方法:
1)configuration.xml , MyBatis主配置文件
1 <?xml version="1.0" encoding="UTF-8"?>
2 /p>
3 "http://mybatis.org/dtd/mybatis-3-config.dtd">
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
2)jdbc.properties
1 driver=com.mysql.jdbc.Driver2 url=jdbc:mysql://localhost:3306/keith
3 username=keith4 password=keith
3)log4j.properties
1 log4j.rootLogger=DEBUG,CONSOLE,FILEOUT2 log4j.addivity.org.apache=true
3
4 # CONSOLE5 log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender6 log4j.appender.Threshold=DEBUG7 log4j.appender.CONSOLE.Target=System.out8 log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout9 #log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n10 log4j.appender.CONSOLE.layout.ConversionPattern=[%-5p] %d{yyyy-MM-dd HH\:mm\:ss} \:%m%n11
12 #13 # FILEOUT14 log4j.appender.FILEOUT=org.apache.log4j.RollingFileAppender15 log4j.appender.FILEOUT.File=${catalina.home}\\file.log16 log4j.appender.fileout.MaxFileSize=100000KB17 # default is true,append to the file; if false, the replace the log file whenever restart system18 log4j.appender.FILEOUT.Append=true
19 #RollingFileAppender没有DatePattern这个属性20 log4j.appender.FILEOUT.layout=org.apache.log4j.PatternLayout21 #log4j.appender.CONSOLE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n22 log4j.appender.FILEOUT.layout.ConversionPattern=[%-5p]_%d{yyyy-MM-dd HH:mm:ss} :%m%n
4)User .java
1 packagecom.mybatis.model;2
3 importjava.io.Serializable;4
5 @SuppressWarnings("serial")6 public class User implementsSerializable {7
8 private intid;9 privateString userName;10 privateString password;11
12 publicUser(){13 }14
15 public intgetId() {16 returnid;17 }18 public void setId(intid) {19 this.id =id;20 }21 publicString getUserName() {22 returnuserName;23 }24 public voidsetUserName(String userName) {25 this.userName =userName;26 }27 publicString getPassword() {28 returnpassword;29 }30 public voidsetPassword(String password) {31 this.password =password;32 }33
34 }
5)UserSqlMap.xml
1 <?xml version="1.0" encoding="UTF-8"?>
2 /p>
4 "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">
5
6
7
8
9
10
11
12
13
14
15
16
17 userName,password18
19
20
21
22 INSERT INTO USER() VALUES(#{userName},#{password})23
24
25
26 UPDATE USER SET userName=#{userName} ,password=#{password} WHERE id=#{id}27
28
29
30 DELETE FROM USER WHERE id=#{id}31
32
33
34 SELECT *FROM USER35
36
37
38
39 SELECT *FROM USER LIMIT #{pageNow},#{pageSize}40
41
42
43 SELECT * FROM USER WHERE id=#{id}44
45
46
47 SELECT count(*) FROM USER48
49
50
51 SELECT * FROM USER WHERE userName=#{userName}52
53
54
6)SessionFactoryUtil.java MyBatis工具类,用于创建SqlSessionFactory
1 packagecom.mybatis.sessionfactory;2
3 importjava.io.IOException;4 importjava.io.Reader;5
6 importorg.apache.ibatis.io.Resources;7 importorg.apache.ibatis.session.SqlSession;8 importorg.apache.ibatis.session.SqlSessionFactory;9 importorg.apache.ibatis.session.SqlSessionFactoryBuilder;10
11 public classSessionFactoryUtil {12
13 private static final String RESOURCE = "Configuration.xml";14 private static SqlSessionFactory sqlSessionFactory = null;15 private static ThreadLocal threadLocal = new ThreadLocal();16
17 static{18 Reader reader = null;19 try{20 reader =Resources.getResourceAsReader(RESOURCE);21 } catch(IOException e) {22 throw new RuntimeException("Get resource error:"+RESOURCE, e);23 }24
25 sqlSessionFactory = newSqlSessionFactoryBuilder().build(reader);26 }27
28 /**
29 * Function : 获得SqlSessionFactory30 */
31 public staticSqlSessionFactory getSqlSessionFactory(){32 returnsqlSessionFactory;33 }34
35 /**
36 * Function : 重新创建SqlSessionFactory37 */
38 public static voidrebuildSqlSessionFactory(){39 Reader reader = null;40 try{41 reader =Resources.getResourceAsReader(RESOURCE);42 } catch(IOException e) {43 throw new RuntimeException("Get resource error:"+RESOURCE, e);44 }45
46 sqlSessionFactory = newSqlSessionFactoryBuilder().build(reader);47 }48
49 /**
50 * Function : 获取sqlSession51 */
52 public staticSqlSession getSession(){53 SqlSession session =threadLocal.get();54
55 if(session!=null){56 if(sqlSessionFactory == null){57 getSqlSessionFactory();58 }59 //如果sqlSessionFactory不为空则获取sqlSession,否则返回null
60 session = (sqlSessionFactory!=null) ? sqlSessionFactory.openSession(): null;61 }62
63 returnsession;64 }65
66 /**
67 * Function : 关闭sqlSession68 */
69 public static voidcloseSession(){70 SqlSession session =threadLocal.get();71 threadLocal.set(null);72 if(session!=null){73 session.close();74 }75 }76 }
7)UserDao interface
1 packagecom.mybatis.dao;2
3 importjava.util.List;4
5 importcom.mybatis.model.User;6
7 public interfaceUserDao {8
9 public User load(intid);10 public voidadd(User user);11 public voidupdate(User user);12 public void delete(intid);13 publicUser findByName(String userName);14 public ListqueryAllUser();15 public List list(int pageNow,intpageSize);16 public intgetAllCount();17
18 }
8)UserDaoImpl
1 packagecom.mybatis.dao.implment;2
3 importjava.util.HashMap;4 importjava.util.List;5 importjava.util.Map;6
7 importorg.apache.ibatis.session.SqlSession;8
9 importcom.mybatis.dao.UserDao;10 importcom.mybatis.model.User;11 importcom.mybatis.sessionfactory.SessionFactoryUtil;12
13
14 public class UserDaoImpl implementsUserDao {15
16 public User load(intid){17 SqlSession session =SessionFactoryUtil.getSqlSessionFactory().openSession();18 User user = (User) session.selectOne("com.mybatis.model.User.selectById_user", id);19 session.close();20 returnuser;21 }22
23 public voidadd(User user) {24 SqlSession session =SessionFactoryUtil.getSqlSessionFactory().openSession();25 session.insert("com.mybatis.model.User.inser_user", user);26 session.commit();27 session.close();28 }29
30 public voidupdate(User user){31 SqlSession session =SessionFactoryUtil.getSqlSessionFactory().openSession();32 session.update("com.mybatis.model.User.update_user", user);33 session.commit();34 session.close();35 }36
37 public void delete(intid){38 SqlSession session =SessionFactoryUtil.getSqlSessionFactory().openSession();39 session.delete("com.mybatis.model.User.delete_user", id);40 session.close();41 }42
43 publicUser findByName(String userName){44 SqlSession session =SessionFactoryUtil.getSqlSessionFactory().openSession();45 User user = (User)session.selectOne("com.mybatis.model.User.selectByName_user", userName);46 session.close();47 returnuser;48 }49
50 @SuppressWarnings("unchecked")51 public ListqueryAllUser() {52 SqlSession session =SessionFactoryUtil.getSqlSessionFactory().openSession();53 List list = session.selectList("com.mybatis.model.User.selectAll_user");54 session.close();55 returnlist;56 }57
58 @SuppressWarnings("unchecked")59 public List list(int pageNow , intpageSize){60 SqlSession session =SessionFactoryUtil.getSqlSessionFactory().openSession();61 Map params = new HashMap();62 params.put("pageNow", pageNow);63 params.put("pageSize", pageSize);64 List list = session.selectList("com.mybatis.model.User.selectList_user", params);65 session.close();66 returnlist;67 }68
69 public intgetAllCount(){70 SqlSession session =SessionFactoryUtil.getSqlSessionFactory().openSession();71 int count = (Integer) session.selectOne("com.mybatis.model.User.selectCount_user");72 session.close();73 returncount;74 }75
76 }
9)测试类:
1 packagecom.mybatis.dao.implment;2
3 importjava.util.List;4
5 importorg.junit.Test;6
7 importcom.mybatis.dao.UserDao;8 importcom.mybatis.model.User;9
10 public classUserDaoTest {11
12 private UserDao userDao = newUserDaoImpl();13
14 @Test15 public voidtestLoad(){16 User u = userDao.load(1);17 if(u!=null){18 System.out.println("UserId:"+u.getId()+" UserName:"+u.getUserName()+" Password:"+u.getPassword());19 }20 else{21 System.out.println("id不存在!!");22 }23 }24
25 @Test26 public voidtestAdd(){27 User user = newUser();28 user.setUserName("admin5");29 user.setPassword("123456");30 userDao.add(user);31 }32
33 @Test34 public voidtestUpdate(){35 User user = newUser();36 user.setId(2);37 user.setUserName("manager");38 user.setPassword("123456");39 userDao.update(user);40 }41
42 @Test43 public voidtestQueryAllUser(){44 List list =userDao.queryAllUser();45 if(list!=null&list.size()>0){46 for(User u:list){47 System.out.println("UserId:"+u.getId()+" UserName:"+u.getUserName()+" Password:"+u.getPassword());48 }49 }50 }51
52 @Test53 public voidtestFindByName(){54 User u = userDao.findByName("admin");55 if(u!=null){56 System.out.println("UserId:"+u.getId()+" UserName:"+u.getUserName()+" Password:"+u.getPassword());57 }58 else{59 System.out.println("用户名不存在!!");60 }61 }62
63 @Test64 public voidtestList(){65 List list = userDao.list(1, 4);66 if(list!=null&list.size()>0){67 for(User u:list){68 System.out.println("UserId:"+u.getId()+" UserName:"+u.getUserName()+" Password:"+u.getPassword());69 }70 }71 }72
73 @Test74 public voidtestGetAllCount(){75 System.out.println("All Count : "+userDao.getAllCount());76 }77
78 @Test79 public voidtestDelete(){80 userDao.delete(3);81 }82
83 }
10)执行testFindByName():
参考至:http://www.open-open.com/lib/view/open1349622424072.html
郁极风在此感谢这位同僚的帮助。