MyBaits 针对于增删改查功能的二次封装
在使用传统的Mybaits 实现JDBC 时候,我们会发现增删改查的代码在有些方面不尽相同,我在这里进行进行了一个简单的二次封装
1.封装一个针对于处理业务逻辑的接口类
总结:
代码如下
package until.factory;
public interface InterfaceExample<T,R> {
R doAnything(T info) throws Exception;
}
2.分别封装针对于两种业务逻辑的处理抽象类
代码如下:
package until.factory;
import com.github.pagehelper.PageHelper;
import until.StaticMessage;
import java.util.HashMap;
import java.util.Map;
public abstract class AbstractSelectFactory<T,R,V,E>{
protected Map<V, InterfaceExample<T,R>> map =new HashMap<>();
public AbstractSelectFactory(int pageSize, int pageNumber) {
PageHelper.startPage(pageNumber,pageSize);
}
protected abstract void init();
protected R goAction(V action,T info) throws Exception {
InterfaceExample<T,R> mapper=map.get(action);
if (mapper!=null) {
return mapper.doAnything(info);
}else{
throw new RuntimeException(StaticMessage.UserExamination.USER_ACTION_NOT_FOUND);
}
}
protected abstract E doAnything(V action,T info) throws Exception;
}
package until.factory;
import until.StaticMessage;
import java.util.HashMap;
import java.util.Map;
public abstract class AbstractDoFactory<T,R,V>{
protected Map<V, InterfaceExample<T,R>> map =new HashMap<>();
protected abstract void init();
public R goAction(V action, T info) throws Exception {
InterfaceExample<T,R> mapper=map.get(action);
R getSuccessResult;
if (mapper != null) {
try {getSuccessResult = mapper.doAnything(info);
} catch (Exception e) {throw new Exception(e.getMessage());}
} else {
throw new RuntimeException(StaticMessage.UserExamination.USER_ACTION_NOT_FOUND);
}
return getSuccessResult;
}
}
3.封装不同业务逻辑的动作参数
package until;
public class ActionName {
public static class UserDoFactoryName{
public static final String CREATE_USER = "create-user";
public static final String USER_LOGIN = "user-login";
}
}
4.封装针对于一张表的代码逻辑
- 针对以增加,修改,删除操作并且针对于用户表的业务逻辑
注意: 我这里是封装成了单例模式的实现
package server.factory;
import com.project.blog.entity.UserModels;
import server.example.UserInsert;
import until.ActionName;
import until.factory.AbstractDoFactory;
public class UserDoFactory extends AbstractDoFactory<UserModels,Integer,String> {
private static UserDoFactory instance;
private UserDoFactory() {}
public static UserDoFactory getInstance() {
if (instance == null) {
try {
instance = new UserDoFactory();
} catch (Exception e) {
e.printStackTrace();
}
}
return instance;
}
@Override
protected void init() {
map.put(ActionName.UserDoFactoryName.CREATE_USER,new UserInsert());
}
}
注意: 我这里是封装成了单例模式的实现
package server.factory;
import com.github.pagehelper.PageInfo;
import com.project.blog.entity.UserModels;
import com.project.blog.entity.UserModelsExample;
import com.project.blog.mapper.UserModelsMapper;
import org.apache.ibatis.session.SqlSession;
import server.example.UserLogin;
import until.ActionName;
import until.MybatisClass;
import until.factory.AbstractSelectFactory;
import java.util.List;
public class UserSelectFactory extends AbstractSelectFactory<UserModels, UserModelsExample, String, PageInfo<UserModels>> {
private static UserSelectFactory userSelectFactory;
private UserSelectFactory(int pageSize, int pageNumber) {
super(pageSize, pageNumber);
}
public static UserSelectFactory getInstance(int pageSize, int pageNumber) {
if (userSelectFactory == null) {
try {
userSelectFactory = new UserSelectFactory(pageSize,pageNumber);
} catch (Exception e) {
e.printStackTrace();
}
}
return userSelectFactory;
}
@Override
public void init() {
map.put(ActionName.UserDoFactoryName.USER_LOGIN,new UserLogin());
}
@Override
public PageInfo<UserModels> doAnything(String action, UserModels info) throws Exception {
PageInfo<UserModels> userModels=new PageInfo<>();
SqlSession sqlSession = MybatisClass.getSqlSession();
UserModelsMapper usersMapper = sqlSession.getMapper(UserModelsMapper.class);
UserModelsExample userModelsExample =goAction(action,info);
try {
List<UserModels> userModelList=usersMapper.selectByExample(userModelsExample);
userModels=new PageInfo<>(userModelList);
} finally {
sqlSession.close();
}
return userModels;
}
}
5.实例代码逻辑实体实现类
注册的代码逻辑
package server.example;
import com.github.pagehelper.PageInfo;
import com.project.blog.entity.UserModels;
import com.project.blog.mapper.UserModelsMapper;
import org.apache.ibatis.session.SqlSession;
import until.MybatisClass;
import until.factory.InterfaceExample;
public class UserInsert implements InterfaceExample<UserModels, Integer> {
@Override
public Integer doAnything(UserModels info) throws Exception {
int success = -1;
PageInfo<UserModels> userModels=null;
SqlSession sqlSession = MybatisClass.getSqlSession();
UserModelsMapper usersMapper = sqlSession.getMapper(UserModelsMapper.class);
try {
success=usersMapper.insert(info);
} finally {sqlSession.close();}
return success;
}
}
登录的代码逻辑
package server.example;
import com.project.blog.entity.UserModels;
import com.project.blog.entity.UserModelsExample;
import until.factory.InterfaceExample;
public class UserLogin implements InterfaceExample<UserModels, UserModelsExample> {
@Override
public UserModelsExample doAnything(UserModels info) throws Exception {
UserModelsExample userModelsExample =new UserModelsExample();
userModelsExample.createCriteria().andUserNameEqualTo(info.getUserName()).andUserPasswordEqualTo(info.getUserPassword());
userModelsExample.setOrderByClause("user_id");
return userModelsExample;
}
}
6.代码调用实例
下面的代码是实现用户登录成功后返回 一个新的session 值,否则返回NULL
package server.server;
import com.project.blog.entity.UserModels;
import server.factory.UserSelectFactory;
import until.ActionName;
import until.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
public class UserLoginServer {
private static UserModels userModels;
private static UserLoginServer userLoginServer;
private UserLoginServer(){
userLoginServer=new UserLoginServer();
userModels=new UserModels();
}
public static UserLoginServer getInstance() {
return userLoginServer;
}
public String login(HttpServletRequest request) throws Exception {
String usernames = request.getParameter("user-name");
String password = request.getParameter("password");
String pageSize = request.getParameter("page-size");
String pageNumber = request.getParameter("page-number");
if (StringUtils.isEmpty(usernames) || StringUtils.isEmpty(password)|| StringUtils.isEmpty(pageSize) || StringUtils.isEmpty(pageNumber)) {
return null;
}else{
userModels.setUserName(usernames);
userModels.setUserPassword(password);
}
int getPageNumber = Integer.parseInt(pageNumber);
int getPageSize = Integer.parseInt(pageSize);
UserSelectFactory userSelectFactory =UserSelectFactory.getInstance(getPageNumber,getPageSize);
userSelectFactory.init();
List<UserModels> users =userSelectFactory.doAnything(ActionName.UserDoFactoryName.USER_LOGIN,userModels).getList();
return users.size()==1? String.valueOf(UUID.randomUUID()):null;
}
}
这个是封装好的String工具类
package until;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
public class StringUtils {
public static boolean isEmpty(String str){
return str == null || str.trim().equals("");
}
public static String cutString(String str,int begin ,int end){
if(str.length() < end || str.length()< begin) return str;
return str.substring(begin,end);
}
public static String pareCode(String str) throws UnsupportedEncodingException{
return new String(str.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
}
}
封装好的返回值如下
package until;
public class StaticMessage {
public static final class UserExamination{
public static final String USER_CREATED_FAITHFULLY = "User registration failed. The user name is duplicate. Please reset";
public static final String USER_ACTION_NOT_FOUND = "Illegal action, please reselect";
}
}
下面是返回Json数据的数据封装包装类
package until;
import javax.servlet.http.HttpServletResponse;
public class RestfulUtil{
private static final int SUCCESS = HttpServletResponse.SC_OK;
private static final int Fail = HttpServletResponse.SC_GONE;
private static final String msg1 = "successful";
private static final String msg2 = "succeed";
public static class Resultant {
private int flagCode;
private String message;
private Object data;
public int getFlag() {
return flagCode;
}
public void setFlag(int flag) {
this.flagCode = flag;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "{" +
"flagCode=" + flagCode +
", message='" + message + '\'' +
", data=" + data +
'}';
}
}
private static Resultant resultant;
public static Resultant getSuccessResult() {
resultant = new Resultant();
resultant.setMessage(msg1);
resultant.setFlag(SUCCESS);
return resultant;
}
public static Resultant getSuccessResult(String message) {
resultant = new Resultant();
resultant.setMessage(message);
resultant.setFlag(SUCCESS);
return resultant;
}
public static Resultant getSuccessResult(Object data) {
resultant = new Resultant();
resultant.setData(data);
resultant.setMessage(msg1);
resultant.setFlag(SUCCESS);
return resultant;
}
public static Resultant getSuccessResult(String message,Object data) {
resultant = new Resultant();
resultant.setData(data);
resultant.setMessage(message);
resultant.setFlag(SUCCESS);
return resultant;
}
public static Resultant getFailResult() {
resultant = new Resultant();
resultant.setMessage(msg2);
resultant.setFlag(Fail);
return resultant;
}
public static Resultant getFailResult(String message) {
resultant = new Resultant();
resultant.setMessage(message);
resultant.setFlag(Fail);
return resultant;
}
public static Resultant getFailResult(String message, Object data) {
resultant = new Resultant();
resultant.setData(data);
resultant.setMessage(message);
resultant.setFlag(Fail);
return resultant;
}
public static Resultant getFreeResult(int code, String message, Object data) {
resultant = new Resultant();
resultant.setData(data);
resultant.setMessage(message);
resultant.setFlag(code);
return resultant;
}
}
下面是附赠的用户注册的调用方式
UserDoFactory userDoFactory = UserDoFactory.getInstance();
userDoFactory.init();
UserModels userModel = new UserModels();
userModel.setUserName("texs");
userModel.setUserPassword("texts");
try {
System.out.println(userDoFactory.goAction(ActionName.UserDoFactoryName.CREATE_USER,userModel));
} catch (Exception e) {
e.printStackTrace();
}
|