MyBatis浅尝笔记
Posted 吕亚辉的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MyBatis浅尝笔记相关的知识,希望对你有一定的参考价值。
MyBatis应属于一种轻量级的java持久层技术,它通过简单的SQL xml或注解,将数据库数据映射到接口与POJO。最近项目要用到mybatis,所以学习之后在这里做个总结,文中的示例以xml配置为主,mybatis也支持注解的方式。
测试数据
先给出demo所使用的表结构,以典型的用户(1)-文章(n)的关系表做demo数据
1 # 2 # mysql数据库:数据库名 :dblog 3 # 4 5 DROP TABLE IF EXISTS m_category; 6 CREATE TABLE m_category ( 7 id int(11) NOT NULL AUTO_INCREMENT, 8 name varchar(64) NOT NULL COMMENT \'分类名称\', 9 parent_id INT NOT NULL , 10 level INT NOT NULL DEFAULT 0, 11 path VARCHAR(64) NOT NULL COMMENT \'栏目路径,rootId-xxId-xxId\', 12 PRIMARY KEY (id) 13 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 14 15 DROP TABLE IF EXISTS m_post; 16 CREATE TABLE m_post ( 17 id int(11) NOT NULL AUTO_INCREMENT, 18 category_id INT NOT NULL , 19 user_id INT NOT NULL , 20 title varchar(64) NOT NULL COMMENT \'标题\', 21 content text COMMENT \'正文\', 22 created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 23 updated_at timestamp NOT NULL DEFAULT \'0000-00-00 00:00:00\', 24 PRIMARY KEY (id) 25 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 26 27 DROP TABLE IF EXISTS m_user; 28 CREATE TABLE m_user ( 29 id int(11) NOT NULL AUTO_INCREMENT, 30 username varchar(64) NOT NULL, 31 password varchar(255) NOT NULL, 32 salt VARCHAR(32) NOT NULL , 33 avatar varchar(64) DEFAULT NULL, 34 type enum(\'customer\',\'admin\',\'root\') NOT NULL DEFAULT \'customer\', 35 remember_token varchar(128) DEFAULT NULL, 36 PRIMARY KEY (id) 37 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8; 38 39 INSERT INTO m_user(id,username, password, salt,type) 40 VALUE (1,\'lvyahui\',\'XXXXXXX\',\'abcs\',\'admin\'); 41 42 DROP TABLE IF EXISTS m_post_comment; 43 CREATE TABLE m_post_comment( 44 id int(11) AUTO_INCREMENT PRIMARY KEY , 45 post_id INT NOT NULL , 46 user_id INT NOT NULL , 47 content VARCHAR(512) NOT NULL DEFAULT \'\', 48 created_at TIMESTAMP NOT NULL DEFAULT current_timestamp, 49 updated_at TIMESTAMP NOT NULL DEFAULT \'0000-00-00 00:00:00\' 50 ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
对应的实体类
Post
1 package org.lyh.java.mybatis.model; 2 3 import java.sql.Timestamp; 4 5 /** 6 * @author lvyahui (lvyahui8@gmail.com,lvyahui8@126.com) 7 * @since 2017/1/1 14:00 8 */ 9 @SuppressWarnings("unused") 10 public class Post extends BaseModel { 11 12 private String title; 13 private String content; 14 private Timestamp createdAt; 15 private Timestamp updatedAt; 16 17 private Integer userId; 18 private Integer categoryId; 19 20 private User user; 21 private Category category; 22 23 public String getTitle() { 24 return title; 25 } 26 27 public void setTitle(String title) { 28 this.title = title; 29 } 30 31 public String getContent() { 32 return content; 33 } 34 35 public void setContent(String content) { 36 this.content = content; 37 } 38 39 public Timestamp getCreatedAt() { 40 return createdAt; 41 } 42 43 public void setCreatedAt(Timestamp createdAt) { 44 this.createdAt = createdAt; 45 } 46 47 public Timestamp getUpdatedAt() { 48 return updatedAt; 49 } 50 51 public void setUpdatedAt(Timestamp updatedAt) { 52 this.updatedAt = updatedAt; 53 } 54 55 public Integer getUserId() { 56 return userId; 57 } 58 59 public void setUserId(Integer userId) { 60 this.userId = userId; 61 } 62 63 public Integer getCategoryId() { 64 return categoryId; 65 } 66 67 public void setCategoryId(Integer categoryId) { 68 this.categoryId = categoryId; 69 } 70 71 public User getUser() { 72 return user; 73 } 74 75 public void setUser(User user) { 76 this.user = user; 77 } 78 79 public Category getCategory() { 80 return category; 81 } 82 83 public void setCategory(Category category) { 84 this.category = category; 85 } 86 87 88 @Override 89 public String toString() { 90 return "Post{" + 91 "title=\'" + title + \'\\\'\' + 92 ", content=\'" + content + \'\\\'\' + 93 ", createdAt=" + createdAt + 94 ", updatedAt=" + updatedAt + 95 ", userId=" + userId + 96 ", categoryId=" + categoryId + 97 \'}\'; 98 } 99 }
User
1 package org.lyh.java.mybatis.model; 2 3 import org.lyh.java.mybatis.type.UserType; 4 5 import java.util.List; 6 7 /** 8 * @author lvyahui (lvyahui8@gmail.com,lvyahui8@126.com) 9 * @since 2017/1/12 22:44 10 */ 11 @SuppressWarnings("unused") 12 public class User extends BaseModel { 13 14 15 private String username; 16 private String password; 17 private String salt; 18 private String avatar; 19 private UserType type; 20 private String rememberToken; 21 22 private List<Post> posts ; 23 private List<PostComment> postComments; 24 25 public String getUsername() { 26 return username; 27 } 28 29 public void setUsername(String username) { 30 this.username = username; 31 } 32 33 public String getPassword() { 34 return password; 35 } 36 37 public void setPassword(String password) { 38 this.password = password; 39 } 40 41 public String getSalt() { 42 return salt; 43 } 44 45 public void setSalt(String salt) { 46 this.salt = salt; 47 } 48 49 public String getAvatar() { 50 return avatar; 51 } 52 53 public void setAvatar(String avatar) { 54 this.avatar = avatar; 55 } 56 57 public UserType getType() { 58 return type; 59 } 60 61 public void setType(UserType type) { 62 this.type = type; 63 } 64 65 public String getRememberToken() { 66 return rememberToken; 67 } 68 69 public void setRememberToken(String rememberToken) { 70 this.rememberToken = rememberToken; 71 } 72 73 public List<Post> getPosts() { 74 return posts; 75 } 76 77 public void setPosts(List<Post> posts) { 78 this.posts = posts; 79 } 80 81 public List<PostComment> getPostComments() { 82 return postComments; 83 } 84 85 public void setPostComments(List<PostComment> postComments) { 86 this.postComments = postComments; 87 } 88 }
一些辅助类
查询条件Condition
1 package org.lyh.java.mybatis.bean; 2 3 /** 4 * @author lvyahui (lvyahui8@gmail.com,lvyahui8@126.com) 5 * @since 2016/12/12 13:27 6 */ 7 @SuppressWarnings("unused") 8 public class Condition { 9 10 private String key; 11 private String opt = "="; 12 private Object value; 13 14 public Condition(String key, String opt, Object value) { 15 this.key = key; 16 this.opt = opt; 17 this.value = value; 18 } 19 20 public Condition(String key, Object value){ 21 this(key,"=",value); 22 } 23 24 public String getKey() { 25 return key; 26 } 27 28 public void setKey(String key) { 29 this.key = key; 30 } 31 32 public String getOpt() { 33 return opt; 34 } 35 36 public void setOpt(String opt) { 37 this.opt = opt; 38 } 39 40 public Object getValue() { 41 return value; 42 } 43 44 public void setValue(Object value) { 45 this.value = value; 46 } 47 }
分页工具类PageData
1 package org.lyh.java.mybatis.bean; 2 3 4 import org.lyh.java.mybatis.model.BaseModel; 5 6 import java.util.List; 7 8 /** 9 * 10 * Created by lvyahui on 2015/7/12. 11 */ 12 @SuppressWarnings("unused") 13 public class PageData<T extends BaseModel> { 14 15 /** 16 * 前端做分页,所以这里limit设置的非常大,相当于不分页 17 */ 18 public static final int DEFAULT_SIZE = 1000; 19 20 private List<T> datas; 21 22 private int currentPage = 1; 23 24 private int totalPage; 25 26 private int totalItem; 27 28 29 private int maxBtnCount = 10; 30 31 private int pageSize = DEFAULT_SIZE; 32 33 private int start = 1; 34 private int end; 35 36 /** 37 * 总项目数 38 */ 39 public int getTotalItem() { 40 return totalItem; 41 } 42 43 public void setTotalItem(int totalItem) { 44 this.totalItem = totalItem; 45 paging(); 46 } 47 48 private void paging() { 49 totalPage = totalItem / pageSize + 1; 50 if(totalPage > maxBtnCount){ 51 if(currentPage <= (maxBtnCount-1)/2){ 52 // 靠近首页 53 start = 1; 54 }else if(totalPage-currentPage < (maxBtnCount-1)/2){ 55 // 靠近尾页 56 start = totalPage - maxBtnCount - 1; 57 }else{ 58 start = currentPage - (maxBtnCount-1)/2; 59 } 60 end = maxBtnCount-1 + start > totalPage ? totalPage : maxBtnCount - 1 + start; 61 }else{ 62 end = totalPage; 63 } 64 // System.out.println("start:"+start+",end:"+end); 65 } 66 67 /** 68 * 总页数 69 */ 70 public int getTotalPage() { 71 return totalPage; 72 } 73 74 /** 75 * 当前页 76 */ 77 public int getCurrentPage() { 78 return currentPage; 79 } 80 81 public void setCurrentPage(int currentPage) { 82 this.currentPage = currentPage; 83 } 84 85 /** 86 * 页面数据 87 */ 88 public List<T> getDatas() { 89 return datas; 90 } 91 92 public void setDatas(List<T> datas) { 93 this.datas = datas; 94 } 95 96 /** 97 * 每页大小,可放多少个项,默认为10 98 */ 99 100 101 public int getPageSize() { 102 return pageSize; 103 } 104 105 public void setPageSize(int pageSize) { 106 this.pageSize = pageSize; 107 } 108 109 /** 110 * @return 最大分页按钮数,默认值为10 111 */ 112 public int getMaxBtnCount() { 113 return maxBtnCount; 114 } 115 116 以上是关于MyBatis浅尝笔记的主要内容,如果未能解决你的问题,请参考以下文章