1. 查詢
除了單條記錄的查詢,這里我們來嘗試查詢一組記錄。
IUserMapper接口添加下面方法:
1
|
List<User> getUsers(String name); |
在User.xml中添加:
1
2
3
4
5
6
7
8
9
10
|
< resultMap type = "User" id = "userList" > <!-- type為返回列表元素的類全名或別名 --> < id column = "id" property = "id" /> < result column = "name" property = "name" /> < result column = "age" property = "age" /> < result column = "address" property = "address" /> </ resultMap > < select id = "getUsers" parameterType = "string" resultMap = "userList" > <!-- resultMap為上面定義的User列表 --> select * from `user` where name like #{name} </ select > |
測試方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Test public void queryListTest() { SqlSession session = sqlSessionFactory.openSession(); try { IUserMapper mapper = session.getMapper(IUserMapper. class ); List<User> users = mapper.getUsers( "%a%" ); // %在sql里代表任意個字符。 for (User user : users) { log.info( "{}: {}" , user.getName(), user.getAddress()); } } finally { session.close(); } } |
如果聯表查詢,返回的是復合對象,需要用association關鍵字來處理。
如User發表Article,每個用戶可以發表多個Article,他們之間是一對多的關系。
(1) 創建Article表,并插入測試數據:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
-- Drop the table if exists DROP TABLE IF EXISTS `Article`; -- Create a table named 'Article' CREATE TABLE `Article` ( `id` int NOT NULL AUTO_INCREMENT, `user_id` int NOT NULL , `title` varchar (100) NOT NULL , `content` text NOT NULL , PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; -- Add several test records INSERT INTO `article` VALUES ( '1' , '1' , 'title1' , 'content1' ), ( '2' , '1' , 'title2' , 'content2' ), ( '3' , '1' , 'title3' , 'content3' ), ( '4' , '1' , 'title4' , 'content4' ); |
(2) com.john.hbatis.model.Article類:
1
2
3
4
5
6
7
|
public class Article { private int id; private User user; private String title; private String content; // Getters and setters are omitted } |
(3) 在IUserMapper中添加:
1
|
List<Article> getArticlesByUserId( int id); |
(4) 在User.xml中添加:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
< resultMap type = "com.john.hbatis.model.Article" id = "articleList" > < id column = "a_id" property = "id" /> < result column = "title" property = "title" /> < result column = "content" property = "content" /> < association property = "user" javaType = "User" > <!-- user屬性映射到User類 --> < id column = "id" property = "id" /> < result column = "name" property = "name" /> < result column = "address" property = "address" /> </ association > </ resultMap > < select id = "getArticlesByUserId" parameterType = "int" resultMap = "articleList" > select u.id, u.name, u.age, u.address, a.id a_id, a.title, a.content from article a inner join user u on a.user_id=u.id and u.id=#{id} </ select > |
(5)測試方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Test public void getArticlesByUserIdTest() { SqlSession session = sqlSessionFactory.openSession(); try { IUserMapper mapper = session.getMapper(IUserMapper. class ); List<Article> articles = mapper.getArticlesByUserId( 1 ); for (Article article : articles) { log.info( "{} - {}, author: {}" , article.getTitle(), article.getContent(), article.getUser().getName()); } } finally { session.close(); } } |
附:
除了在association標簽內定義字段和屬性的映射外,還可以重用User的resultMap:
1
|
< association property = "user" javaType = "User" resultMap = "userList" /> |
2. 新增
IUserMapper接口添加下面方法:
int addUser(User user);
User.xml添加:
1
2
3
|
< insert id = "addUser" parameterType = "User" useGeneratedKeys = "true" keyProperty = "id" > <!-- useGeneratedKeys指定myBatis使用數據庫自動生成的主鍵,并填充到keyProperty指定的屬性上。如果未指定,返回對象拿不到生成的值 --> insert into user(name,age,address) values(#{name},#{age},#{address}) </ insert > |
測試方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
|
@Test public void addUserTest() { User user = new User( "Lucy" , 102 , "Happy District" ); SqlSession session = sqlSessionFactory.openSession(); try { IUserMapper mapper = session.getMapper(IUserMapper. class ); int affectedCount = mapper.addUser(user); session.commit(); // 默認為不自動提交。調用session.getConnection().getAutoCommit()查看 log.info( "{} new record was inserted successfully whose id: {}" , affectedCount, user.getId()); } finally { session.close(); } } |
3. 更新
接口添加方法:
1
|
int updateUser(User user); |
User.xml添加:
1
2
3
4
|
< update id = "updateUser" parameterType = "User" > update `user` set name=#{name}, age=#{age}, address=#{address} where id=#{id} </ update > |
測試方法:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
@Test public void updateUserTest() { SqlSession session = sqlSessionFactory.openSession(); try { IUserMapper mapper = session.getMapper(IUserMapper. class ); User user = mapper.getUserById( 8 ); user.setAddress( "Satisfied District" ); int affectedCount = mapper.updateUser(user); // 除了要修改的屬性外,user的其它屬性也要賦值,否則這些屬性會被數據庫更新為初始值(null或0等),可以先查詢一次,但這樣會增加和數據庫不必要的交互。后面的條件判斷能避免此問題。 log.info( "Affected count: {}" , affectedCount); session.commit(); } finally { session.close(); } } |
4. 刪除
接口添加方法:
1
|
int deleteUser( int id); |
User.xml添加:
1
2
3
|
< delete id = "deleteUser" parameterType = "int" > delete from `user` where id=#{id} </ delete > |
測試方法:
1
2
3
4
5
6
7
8
9
10
11
12
|
@Test public void deleteUserTest() { SqlSession session = sqlSessionFactory.openSession(); try { IUserMapper mapper = session.getMapper(IUserMapper. class ); int affectedCount = mapper.deleteUser( 8 ); log.info( "Affected count: {}" , affectedCount); session.commit(); } finally { session.close(); } } |