Java通過MyBatis框架對MySQL數(shù)據(jù)進(jìn)行增刪查改的基本方法
1. 查詢
除了單條記錄的查詢,這里我們來嘗試查詢一組記錄。
IUserMapper接口添加下面方法:
List<User> getUsers(String name);
在User.xml中添加:
<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>
測試方法:
@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();
}
}
如果聯(lián)表查詢,返回的是復(fù)合對象,需要用association關(guān)鍵字來處理。
如User發(fā)表Article,每個用戶可以發(fā)表多個Article,他們之間是一對多的關(guān)系。
(1) 創(chuàng)建Article表,并插入測試數(shù)據(jù):
-- 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類:
public class Article {
private int id;
private User user;
private String title;
private String content;
// Getters and setters are omitted
}
(3) 在IUserMapper中添加:
List<Article> getArticlesByUserId(int id);
(4) 在User.xml中添加:
<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)測試方法:
@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標(biāo)簽內(nèi)定義字段和屬性的映射外,還可以重用User的resultMap:
<association property="user" javaType="User" resultMap="userList" />
2. 新增
IUserMapper接口添加下面方法:
int addUser(User user);
User.xml添加:
<insert id="addUser" parameterType="User" useGeneratedKeys="true" keyProperty="id"><!-- useGeneratedKeys指定myBatis使用數(shù)據(jù)庫自動生成的主鍵,并填充到keyProperty指定的屬性上。如果未指定,返回對象拿不到生成的值 -->
insert into user(name,age,address) values(#{name},#{age},#{address})
</insert>
測試方法:
@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(); // 默認(rèn)為不自動提交。調(diào)用session.getConnection().getAutoCommit()查看
log.info("{} new record was inserted successfully whose id: {}", affectedCount, user.getId());
} finally {
session.close();
}
}
3. 更新
接口添加方法:
int updateUser(User user);
User.xml添加:
<update id="updateUser" parameterType="User">
update `user` set name=#{name}, age=#{age}, address=#{address}
where id=#{id}
</update>
測試方法:
@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的其它屬性也要賦值,否則這些屬性會被數(shù)據(jù)庫更新為初始值(null或0等),可以先查詢一次,但這樣會增加和數(shù)據(jù)庫不必要的交互。后面的條件判斷能避免此問題。
log.info("Affected count: {}", affectedCount);
session.commit();
} finally {
session.close();
}
}
4. 刪除
接口添加方法:
int deleteUser(int id);
User.xml添加:
<delete id="deleteUser" parameterType="int">
delete from `user` where id=#{id}
</delete>
測試方法:
@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();
}
}
相關(guān)文章
Shiro:自定義Realm實(shí)現(xiàn)權(quán)限管理方式
這篇文章主要介紹了Shiro:自定義Realm實(shí)現(xiàn)權(quán)限管理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
java實(shí)現(xiàn)Dijkstra最短路徑算法
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)Dijkstra最短路徑算法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-01-01
Java中常用解析工具jackson及fastjson的使用
今天給大家?guī)淼氖顷P(guān)于Java解析工具的相關(guān)知識,文章圍繞著jackson及fastjson的使用展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下2021-06-06
SpringBoot集成yitter-idgenerator(雪花漂移)分布式Id自增的實(shí)現(xiàn)
本文主要介紹了SpringBoot集成yitter-idgenerator(雪花漂移)分布式Id自增的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01
Spring Boot使用AOP實(shí)現(xiàn)REST接口簡易靈活的安全認(rèn)證的方法
這篇文章主要介紹了Spring Boot使用AOP實(shí)現(xiàn)REST接口簡易靈活的安全認(rèn)證的方法,非常具有實(shí)用價值,需要的朋友可以參考下2018-11-11
java原生序列化和Kryo序列化性能實(shí)例對比分析
這篇文章主要介紹了java原生序列化和Kryo序列化性能實(shí)例對比分析,涉及Java和kryo序列化和反序列化相關(guān)實(shí)例,小編覺得很不錯,這里分享給大家,希望給大家一個參考。2017-10-10

