手写一个Spring框架(不含AOP)

spring 手写分三个阶段:

1.配置阶段:

web.xml配置

servlet初始化

2.初始化阶段:

加载配置文件

ioc容器初始化

扫描相关的类

类实例化,并注入ioc容器

将url路径和相关method进行映射关联

3运行阶段

dopost作为入口

根据url找到method,通过反射去运行method;

response.getWriter(().wirte();

 

项目结构图如下:

一.配置阶段:

项目本身是maven项目,pom文件只配了servlet-api和jetty

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.wj.Spring</groupId>
    <artifactId>Spring</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

    </dependencies>
    <build>
        <plugins>
        <plugin>
            <groupId>org.eclipse.jetty</groupId>
            <artifactId>jetty-maven-plugin</artifactId>
            <version>9.4.5.v20170502</version>
            <configuration>
                <scanIntervalSeconds>10</scanIntervalSeconds>
                <httpConnector>
                    <port>8080</port>
                </httpConnector>
                <webApp>
                    <contextPath>/</contextPath>
                </webApp>
            </configuration>
        </plugin>
        </plugins>
    </build>
</project>

然后创建DispatcherServlet 使其继承HttpServlet,重写dopost,doGet 以及 init 方法


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

      
    }

    @Override
    public void init(ServletConfig config) throws ServletException {

    }

配置web.xml  如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">


    <servlet>
        <servlet-name>demoMvc</servlet-name>
        <servlet-class>com.wj.spring.mvcframework.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>application.properties</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>demoMvc</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>


</web-app>

配置spring 核心配置文件application的路径

application.properties的内容只有一个扫描路径:

接下来配置注解:springMvc常用注解:

@Controller  @Service @RequestMapping  @Autowired  @RequestParam

这些我们都将重写,替换成自己的注解

1)@DemoController

package com.wj.spring.mvcframework.annotation;

import java.lang.annotation.*;

/**
 * Created by 小美女 on 2018/12/9.
 */

//类上使用
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoController {

    String value() default "";
}

2)@DemoService

package com.wj.spring.mvcframework.annotation;

import java.lang.annotation.*;

/**
 * Created by 小美女 on 2018/12/9.
 */

//类上使用
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoService {

    String value() default "";
}

3) @DemoRequestMapping

package com.wj.spring.mvcframework.annotation;

import java.lang.annotation.*;

/**
 * Created by 小美女 on 2018/12/9.
 */
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoRequestMapping {
    String value() default "";
}

4)@Autowired

package com.wj.spring.mvcframework.annotation;

import java.lang.annotation.*;

/**
 * Created by 小美女 on 2018/12/9.
 */
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoAutowired {
    String value() default "";
}

5) @DemoRequestParam    该注解因为在配置时把参数名字写死了,所以下文没用上

package com.wj.spring.mvcframework.annotation;

import java.lang.annotation.*;

/**
 * Created by 小美女 on 2018/12/9.
 */
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DemoRequestParam {
    String value() default "";
}

创建测试类:DemoAction  ;  DemoServiceImpl implements MyService

1)DemoAction:

package com.wj.spring.demo.action;

import com.wj.spring.demo.service.MyService;
import com.wj.spring.mvcframework.annotation.DemoAutowired;
import com.wj.spring.mvcframework.annotation.DemoController;
import com.wj.spring.mvcframework.annotation.DemoRequestMapping;
import com.wj.spring.mvcframework.annotation.DemoRequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by 小美女 on 2018/12/9.
 */
@DemoController
@DemoRequestMapping("/demo")
public class DemoAction {

    @DemoAutowired
    private MyService myService;
    @DemoRequestMapping("/query")
    public void query(HttpServletRequest req, HttpServletResponse resp,@DemoRequestParam("name") String name){
        String result =myService.get(name);
        try {

            //写入页面
            resp.getWriter().write(result);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @DemoRequestMapping("/add")
    public void add(HttpServletRequest req,HttpServletResponse resp,@DemoRequestParam("a") Integer a,@DemoRequestParam("b") Integer b){
        try {

            resp.getWriter().write(a+"+"+b+"="+(a+b));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @DemoRequestMapping("/remove")
    public void remove(HttpServletRequest req,HttpServletResponse resp,@DemoRequestParam("id") Integer id){

    }

}

2)MyService:

package com.wj.spring.demo.service;


/**
 * Created by 小美女 on 2018/12/9.
 */
public interface MyService {
    public String get(String name);
}

3) DemoServiceImpl implements MyService:

package com.wj.spring.demo.service.impl;

import com.wj.spring.demo.service.MyService;
import com.wj.spring.mvcframework.annotation.DemoService;

/**
 * Created by 小美女 on 2018/12/9.
 */
@DemoService
public class DemoServiceImpl implements MyService {
    public String get(String name) {
        return "my name is :"+name;
    }
}

2.初始化阶段:

在DispatcherServlet中添加成员变量;

 

当web项目启动时,会启动Servlet容器并加载DispatcherServlet 的init()方法,从init()方法的参数中,我们可以拿到application.properties文件的路径,并读取其中的属性(扫描路径);在init()方法中添加初始化内容:

 @Override
    public void init(ServletConfig config) throws ServletException {
        //1.加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //2.扫描相关类(解析配置)
        doScanner(contextConfig.getProperty("scanPackage"));

        //3.初始化扫描到的类,并且把他们加载到IOC容器中
        doInstance();

        //4.实现依赖注入(自动赋值)
        doAutowired();

        //5.初始化handlerMapping
        initHandlerMapping();


        System.out.println("my Spring init");
    }

1)doLoadConfig()方法,将配置文件读取到Pripeties 中

private void doLoadConfig(String contextConfigLocation) {
        //反射加载过程有讲到过读取classPath下的配置文件方法
        InputStream is =  this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);

        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

2)doScanner(),递归扫描所有的Class文件

   private void doScanner(String scanPackage) {
        //得到一个url(将所有的“.“替换成”/“)
        URL url =  this.getClass().getClassLoader().getResource("/"+scanPackage.replaceAll("\\.","/"));
        File classDir = new File(url.getFile());
        for(File file :classDir.listFiles()){
            if(file.isDirectory()){ //如果是文件夹
                //递归
                doScanner(scanPackage+"."+file.getName());

            }else{
                if(file.getName().endsWith(".class")){ //如果不是文件夹,是文件
                  String className =     (scanPackage+"."+file.getName()).replace(".class","");
                  //获取到所有class文件的路径,存入一个list中
                  classNames.add(className);
                }
            }

        }

    }

3)doInstance()方法,初始化相关的类,并将其放入Ioc容器中(一个map)ioc的key默认是类名首字母小写,为此还写了个lowerFirstCase(String beanName) 方法:

 private void doInstance() {
        //将扫描到的类进行反射
        try {
            if(classNames.isEmpty()){
                return;
            }

            for(String className : classNames){
                Class<?> clazz = Class.forName(className);
                //将实例化后的对象保存进IOC容器;

                if(clazz.isAnnotationPresent(DemoController.class)){
                    Object o = clazz.newInstance();
                    //类名首字母小写,建立一个lowerFirstCase方法(转换成char[] 数组操作  chars[0]+=32)
                    String beanName = lowerFirstCase(clazz.getSimpleName());
                    ioc.put(beanName,o);
                }else if(clazz.isAnnotationPresent(DemoService.class)){
                    // service 注入的不是他本身,而是它的实现类
                    //1.默认类名首字母小写(Interface)

                    //2.自定义beanName;
                    DemoService demoService = clazz.getAnnotation(DemoService.class);
                    String beanName = demoService.value();
                    if("".equals(beanName)){
                        beanName = lowerFirstCase(clazz.getSimpleName());
                    }
                    Object o = clazz.newInstance();
                    ioc.put(beanName,o);
                    //3. 如果是接口的实现(impl)的话,用他的接口类型作为key
                    Class<?>[] interfaces =  clazz.getInterfaces();
                    for(Class<?> i :interfaces){
                        //如果一个接口有多个实现类,会出现重复的情况
                        if(ioc.containsKey(i.getName())){
                            throw  new Exception("The beanName is exists");
                        }
                        ioc.put(i.getName(),o);
                    }
                }else{
                    continue;
                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private String lowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        chars[0]+=32;
        return  String.valueOf(chars);
    }
 

4)doAutowired()方法,为Ioc容器中类的属性赋值

    private void doAutowired() {
        if(ioc.isEmpty()){
            return;
        }

        for(Map.Entry<String,Object> entry:ioc.entrySet()){
            //获取所有属性(包括私有)
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for(Field field :fields){
                //只注入Autowired注解
                if(!field.isAnnotationPresent(DemoAutowired.class)){continue;}

                DemoAutowired demoAutowired = field.getAnnotation(DemoAutowired.class);
                String beanName = demoAutowired.value().trim();
                if("".equals(beanName)){//如果注解里的属性名是空的话,使用类名

                    beanName = field.getType().getName();
                }


                field.setAccessible(true);
                try {
                    //使用反射为属性赋值
                    field.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

    }

5)initHandlerMapping()方法,将访问时的url和DemoAction 的方法关联

private void initHandlerMapping() {
        //找到方法路径
        if(ioc.isEmpty()){return;}

        for(Map.Entry<String,Object> entry : ioc.entrySet()){
            Class<?> clazz = entry.getValue().getClass();
            if(!clazz.isAnnotationPresent(DemoController.class)){
                continue;
            }
            String baseUrl = "";
            if(clazz.isAnnotationPresent(DemoRequestMapping.class)){
                DemoRequestMapping demoRequestMapping = clazz.getAnnotation(DemoRequestMapping.class);
                baseUrl = demoRequestMapping.value();
            }


            //这里不需要获取private的方法,Spring源码中也是这样的
            Method[] methods = clazz.getMethods();

            for(Method method:methods){
                //只用requestMapping 的方法才需要映射
                if(!method.isAnnotationPresent(DemoRequestMapping.class)){
                    continue;
                }

                DemoRequestMapping demoRequestMapping = method.getAnnotation(DemoRequestMapping.class);
                //多个“/” 替换成一个“/”;
                String url  = ("/"+baseUrl+"/"+demoRequestMapping.value()).replaceAll("/+","/");

                handlerMapping.put(url,method);
                System.out.println("Mapped:"+url+","+method);
            }

        }


    }

3.运行阶段

运行时,用户发送的请求都会被DispatcherServlet 接受,统一调用dopost方法,因此在dopost()方法中添加doDispatch()方法

 @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //运行阶段,根据用户请求的url,进行调动
        try {
            doDispatch(req,resp);
        }catch (Exception e){
            e.printStackTrace();
            resp.getWriter().write("500 Detail:"+ Arrays.toString(e.getStackTrace()));
        }

    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        if(this.handlerMapping.isEmpty()){return;}
        //绝对路径
        String url =  req.getRequestURI();

        //绝对路径处理成相对路径
        String contextPath = req.getContextPath();
        url =  url.replace(contextPath,"").replaceAll("/+","/");

        if(!this.handlerMapping.containsKey(url)){
            resp.getWriter().write("404 NOT FOUND");
            return;
        }

        Method method =this.handlerMapping.get(url);
        //反射调用
        //1.方法所在类的实例(从IOC容器中拿)
        //这里没有办法获得IOCmap中的key,只能通过方法所在类的类名首字母小写获得,与Spring的方法不同
        String beanName = lowerFirstCase(method.getDeclaringClass().getSimpleName());

        //浏览器参数
        Map<String,String[]>params = new HashMap<String, String[]>();
        params = req.getParameterMap();
        method.invoke(ioc.get(beanName),new Object[]{req,resp,params.get("name")[0]});

    }

到此整个配置完成;在浏览器输入地址:

 

以下是DispatcherServlet的全部代码:

package com.wj.spring.mvcframework.servlet;

import com.wj.spring.mvcframework.annotation.DemoAutowired;
import com.wj.spring.mvcframework.annotation.DemoController;
import com.wj.spring.mvcframework.annotation.DemoRequestMapping;
import com.wj.spring.mvcframework.annotation.DemoService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * Created by 小美女 on 2018/12/9.
 */
public class DispatcherServlet extends HttpServlet{


    private Properties contextConfig = new Properties();

    private List<String> classNames = new ArrayList<String>();


    //ioc容器
    Map<String,Object> ioc = new HashMap<String, Object>();


    //类里面的方法集合
    Map<String,Method> handlerMapping = new HashMap<String, Method>();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //运行阶段,根据用户请求的url,进行调动
        try {
            doDispatch(req,resp);
        }catch (Exception e){
            e.printStackTrace();
            resp.getWriter().write("500 Detail:"+ Arrays.toString(e.getStackTrace()));
        }

    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException, InvocationTargetException, IllegalAccessException {
        if(this.handlerMapping.isEmpty()){return;}
        //绝对路径
        String url =  req.getRequestURI();

        //绝对路径处理成相对路径
        String contextPath = req.getContextPath();
        url =  url.replace(contextPath,"").replaceAll("/+","/");

        if(!this.handlerMapping.containsKey(url)){
            resp.getWriter().write("404 NOT FOUND");
            return;
        }

        Method method =this.handlerMapping.get(url);
        //反射调用
        //1.方法所在类的实例(从IOC容器中拿)
        //这里没有办法获得IOCmap中的key,只能通过方法所在类的类名首字母小写获得,与Spring的方法不同
        String beanName = lowerFirstCase(method.getDeclaringClass().getSimpleName());

        //浏览器参数
        Map<String,String[]>params = new HashMap<String, String[]>();
        params = req.getParameterMap();
        method.invoke(ioc.get(beanName),new Object[]{req,resp,params.get("name")[0]});

    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        //1.加载配置文件
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //2.扫描相关类(解析配置)
        doScanner(contextConfig.getProperty("scanPackage"));

        //3.初始化扫描到的类,并且把他们加载到IOC容器中
        doInstance();

        //4.实现依赖注入(自动赋值)
        doAutowired();

        //5.初始化handlerMapping
        initHandlerMapping();


        System.out.println("my Spring init");
    }

    private void initHandlerMapping() {
        //找到方法路径
        if(ioc.isEmpty()){return;}

        for(Map.Entry<String,Object> entry : ioc.entrySet()){
            Class<?> clazz = entry.getValue().getClass();
            if(!clazz.isAnnotationPresent(DemoController.class)){
                continue;
            }
            String baseUrl = "";
            if(clazz.isAnnotationPresent(DemoRequestMapping.class)){
                DemoRequestMapping demoRequestMapping = clazz.getAnnotation(DemoRequestMapping.class);
                baseUrl = demoRequestMapping.value();
            }


            //这里不需要获取private的方法,Spring源码中也是这样的
            Method[] methods = clazz.getMethods();

            for(Method method:methods){
                //只用requestMapping 的方法才需要映射
                if(!method.isAnnotationPresent(DemoRequestMapping.class)){
                    continue;
                }

                DemoRequestMapping demoRequestMapping = method.getAnnotation(DemoRequestMapping.class);
                //多个“/” 替换成一个“/”;
                String url  = ("/"+baseUrl+"/"+demoRequestMapping.value()).replaceAll("/+","/");

                handlerMapping.put(url,method);
                System.out.println("Mapped:"+url+","+method);
            }

        }


    }

    private void doAutowired() {
        if(ioc.isEmpty()){
            return;
        }

        for(Map.Entry<String,Object> entry:ioc.entrySet()){
            //获取所有属性(包括私有)
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            for(Field field :fields){
                //只注入Autowired注解
                if(!field.isAnnotationPresent(DemoAutowired.class)){continue;}

                DemoAutowired demoAutowired = field.getAnnotation(DemoAutowired.class);
                String beanName = demoAutowired.value().trim();
                if("".equals(beanName)){//如果注解里的属性名是空的话,使用类名

                    beanName = field.getType().getName();
                }


                field.setAccessible(true);
                try {
                    //使用反射为属性赋值
                    field.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    private void doInstance() {
        //将扫描到的类进行反射
        try {
            if(classNames.isEmpty()){
                return;
            }

            for(String className : classNames){
                Class<?> clazz = Class.forName(className);
                //将实例化后的对象保存进IOC容器;

                if(clazz.isAnnotationPresent(DemoController.class)){
                    Object o = clazz.newInstance();
                    //类名首字母小写,建立一个lowerFirstCase方法(转换成char[] 数组操作  chars[0]+=32)
                    String beanName = lowerFirstCase(clazz.getSimpleName());
                    ioc.put(beanName,o);
                }else if(clazz.isAnnotationPresent(DemoService.class)){
                    // service 注入的不是他本身,而是它的实现类
                    //1.默认类名首字母小写(Interface)

                    //2.自定义beanName;
                    DemoService demoService = clazz.getAnnotation(DemoService.class);
                    String beanName = demoService.value();
                    if("".equals(beanName)){
                        beanName = lowerFirstCase(clazz.getSimpleName());
                    }
                    Object o = clazz.newInstance();
                    ioc.put(beanName,o);
                    //3. 如果是接口的实现(impl)的话,用他的接口类型作为key
                    Class<?>[] interfaces =  clazz.getInterfaces();
                    for(Class<?> i :interfaces){
                        //如果一个接口有多个实现类,会出现重复的情况
                        if(ioc.containsKey(i.getName())){
                            throw  new Exception("The beanName is exists");
                        }
                        ioc.put(i.getName(),o);
                    }
                }else{
                    continue;
                }

            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private String lowerFirstCase(String simpleName) {
        char[] chars = simpleName.toCharArray();
        chars[0]+=32;
        return  String.valueOf(chars);
    }

    private void doScanner(String scanPackage) {
        //得到一个url(将所有的“.“替换成”/“)
        URL url =  this.getClass().getClassLoader().getResource("/"+scanPackage.replaceAll("\\.","/"));
        File classDir = new File(url.getFile());
        for(File file :classDir.listFiles()){
            if(file.isDirectory()){ //如果是文件夹
                //递归
                doScanner(scanPackage+"."+file.getName());

            }else{
                if(file.getName().endsWith(".class")){ //如果不是文件夹,是文件
                  String className =     (scanPackage+"."+file.getName()).replace(".class","");
                  //获取到所有class文件的路径,存入一个list中
                  classNames.add(className);
                }
            }

        }

    }

    private void doLoadConfig(String contextConfigLocation) {
        //反射加载过程有讲到过读取classPath下的配置文件方法
        InputStream is =  this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);

        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一、SBORM 介绍 1、目前只考虑支持 mysql; 2、基于spring jdbc的上层封装,底层jdbc操作基于JdbcTemplate,对于使用spring jdbc的人会有一点价值,比较简洁的封装可以节省很多重复劳动,具体节省多少可以看看example; 3、实现一套简单的ORM(直接使用spring rowmapper,insert自己实现),可以基于对象进行crud和相对复杂(感觉比hibernate强大一点)的sql操作; 4、基于对象指定查询的字段,大部分时候可以忘掉表结构进行业务开发; 5、支持简单的数据库路由,读写分离(半自动,需要指定取writer还是reader,默认规则reader采用随机的方式,当然也可以手动指定); 6、支持简单的分表,主要是针对一定规则的分表,比如百分表、千分表,也可以自己指定分表后缀; 7、简单的单表查询(比如所有条件是and或者or结构),基本实现0sql代码编写(类似HibernateTemplate selectByExample、findByCriteria、find等方法); 8、简单的单表排序支持,支持多个排序条件组合; 9、对于复杂的sql查询,提供获取jdbctemplate实例进行操作,类似spring jdbc的常规用法; 10、提供Entity代码生成接口,Entity并非简单的pojo(尽可能不要去修改此类),引入字段常量类,方便查询的时候指定选择字段,从而更好实现查询条件的封装; 二、为什么写SBORM? 1、hibernate:过于臃肿,使用不够灵活,优化难(其实主要是因为很少用),HQL感觉就是个渣,在 mysql几乎一统天下的背景下,跨数据库级别的兼容吃力不讨好。Hibernate的对象化关联处理确实挺强大,但是使用起来坑太多,有多少人敢在项目 中大范围使用真不知道,屠龙刀不是人人都提的起啊。 2、mybatis:轻量级,基于xml的模式感觉不利于封装,代码量不小,基于xml维护也麻烦(个人观点, 现在注解模式貌似也挺不错),感觉mybatis更适合存在dba角色的年代,可以远离代码进行sql调优,复杂的查询拼装起来也更加优雅(java基本 就是if else ...),但是对于查询业务简单但是数据库集群环境的场景有点憋屈(其实对mybatis使用也不多,瞎评论^_^)。 3、spring jdbc:小巧,灵活,足够优秀,个人比较喜欢使用,但是代码量偏大,原生的接口重复劳动量大,比如insert、mapper之类的; SBORM只是针对spring jdbc的一些不方便的地方,做了一些封装,更加简化日常的开发工作,基于spring jdbc的RowMapper自动实现对象映射,也勉强算的上叫ORM,只是大部分功能已经由spring jdbc实现了。 平时不太喜欢使用hibernate和mybatis,主要是使用spring jdbc,写这个东西的出发点主要是平时使用spring jdbc觉 得比较麻烦,重复性的代码偏多,一方面通过自动mapper降低返回结果处理工作量,另一方面参考hibernate对象化查询条件的模式,写了一个 QueryBudiler,使得更多简单的单表查询可以通过对象组织查询、更改逻辑,避免过多去写相似性的SQL语句,减少DAO接口量。 三、一些亮点 1、Entity的设计:很多人看了也许会说,这个不是POJO,不是纯粹的Java Bean,显得很另类。但是有多人在开发过程中(特别是在写sql的时候),经常要去看看表结构设计?还有多少次因为改了表某个字段,还得遍历去查找哪些 sql使用了这个字段?多少次看到在代码中直接传入字段名作为查询参数感到别扭?如果将表结构字段都用java对象去描述,能够解决这些问题,就不必要在 乎是不是POJO了,后面看example的时候应该能体会这么做的一些好处,至少我觉得是挺方便的,将大部分查询脱离表结构设计。 2、简单的数据库路由:如果分库结构不是太复杂(比如简单的读写分离、或者多个库集成),BaseDao可以自 动进行路由(比如读写分离,根据业务模式指定读、写库),如果非默认的路由规则,也可以通过手动设置的模式,进行数据库路由。数据库路由直接由 Entity指定,所有的路由都是根据Entity识别,也就是说查询也是围绕Entity展开的,避免类似使用spring jdbc的时候,各种 template实例跳来跳去,硬编码引入,写一个业务还得看看到底该用哪个template,尤其是多个数据库共用一个template实例的时候。 3、QueryBuilder:单表查询基本上都可以实现零Sql(除非查询条件特别复杂的),更新、删除等操作也可以通过QueryBuilder进行批量处理,不局限于根据主键来处理。 4、分表操作的支持:对于分表操作和常规的使用没有区别,只是指定分表规则,mybatis好像也可以通过制定参数实现分表处理,没搞清楚hibernate对这个是怎么处理的(hibernate好像是bean和表一对一绑定的)? 标签:sborm

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值