druid + mybatis-spring使用注解方式整合
<dependencyManagement> <dependencies> <!--mysql驱动依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <!--连接池依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency> <!--mybatis依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency> <!--spring依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <!--spring-jdcb依赖--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!--mybatis-spring依赖--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>${mybatis.spring.version}</version> </dependency> <!--servlet依赖--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.version}</version> </dependency> <!--gson依赖--> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>${gson.version}</version> </dependency> </dependencies> </dependencyManagement>
因为mybatis-spring用到了spring-jdbc里面的东西,所以需要导入依赖
依赖版本如下:
<spring.version>5.2.0.RELEASE</spring.version> <druid.version>1.1.20</druid.version> <mybatis.version>3.5.2</mybatis.version> <junit.version>4.12</junit.version> <servlet.version>3.1.0</servlet.version> <mysql.version>5.1.47</mysql.version> <gson.version>2.8.5</gson.version> <mybatis.spring.version>2.0.2</mybatis.spring.version>
创建出各个模块:entity,util,dao,service,web(按需求增加或减少,不是一定的)
给每个模块的pom.xml文件添加对应需要的依赖。
3、模块操作
3-1 编写entity模块
将需要的实体类编写,添加相应的属性,getter(),setter(),toString()....方法。
3-2 编写util模块
ApplicationContextHolder类:
package com.spring; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class ApplicationContextHolder implements ApplicationContextAware { private static ApplicationContext context; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.context = applicationContext; } public ApplicationContext getContext(){ return context; } public static <T>T getBean(String name,Class<?> clz){ return (T) context.getBean(name,clz); } }
DruidDateSourceFactoryBean类:这个类等价于在applicationContext.xml中直接配置DruidDataSource的bean。
package com.spring; import com.alibaba.druid.pool.DruidDataSource; import org.springframework.beans.factory.FactoryBean; import javax.sql.DataSource; public class DruidDateSourceFactoryBean implements FactoryBean<DataSource> { @Override public DataSource getObject() throws Exception { DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mysql://localhost:3306/empdb"); dataSource.setUsername("root"); dataSource.setPassword("root"); return dataSource; } @Override public Class<?> getObjectType() { return DataSource.class; } @Override public boolean isSingleton() { return true; } }
3-3 编写dao模块
EmpDao接口:
package com.dao; import com.entity.Employee; import org.apache.ibatis.annotations.Select; import java.util.List; public interface EmpDao { //使用注解方式使用查询语句 @Select("select id,username,salary,gender,hiredate,deptid from employee") List<Employee> queryAll(); }
EmpService接口:
package com.service; import com.entity.Employee; import java.util.List; public interface EmpService { List<Employee> queryAll(); }
EmpServiceImpl实现类:
package com.service.impl; import com.dao.EmpDao; import com.entity.Employee; import com.service.EmpService; import java.util.List; public class EmpServiceImpl implements EmpService { private EmpDao empDao; //通过依赖注入empDao public void setEmpDao(EmpDao empDao) { this.empDao = empDao; } @Override public List<Employee> queryAll() { return empDao.queryAll(); } }
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!--dataSource的bean--> <bean id="dataSource" class="com.spring.DruidDateSourceFactoryBean"></bean> <!--创建sqlSessionFactory的bean,并且把dataSource通过属性注入进去--> <bean id="sqlSessionFatory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> </bean> <!--通过MapperFactoryBean类,属性注入接口类型和sqlSessionFactory创建出dao接口的bean--> <bean id="empDao" class="org.mybatis.spring.mapper.MapperFactoryBean"> <property name="mapperInterface" value="com.dao.EmpDao"/> <property name="sqlSessionFactory" ref="sqlSessionFatory"/> </bean> <!--创建empService的bean,属性注入empDao--> <bean id="empService" class="com.service.impl.EmpServiceImpl"> <property name="empDao" ref="empDao"></property> </bean> <bean class="com.spring.ApplicationContextHolder"></bean> </beans>
3-5 编写web模块
LoginServlet类:
package com.web; import com.entity.Employee; import com.google.gson.Gson; import com.service.EmpService; import com.service.impl.EmpServiceImpl; import com.spring.ApplicationContextHolder; import org.springframework.context.ApplicationContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; @WebServlet("/select") public class LoginServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("UTF-8"); EmpService empService = ApplicationContextHolder.getBean("empService",EmpService.class); List<Employee> employees = empService.queryAll(); Gson gson = new Gson(); resp.getWriter().write(gson.toJson(employees)); } }
ApplicationContextInstantiateListener监听器类:
package com.web; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; public class ApplicationContextInstantiateListener implements ServletContextListener { //context对象setAttribute的名字 private static final String SPRING_CONTAINER_KEY = "SPRING_CONTAINER"; @Override public void contextInitialized(ServletContextEvent servletContextEvent) { //得到上下文对象 ServletContext servletContext = servletContextEvent.getServletContext(); //得到上下文对象的值,我们在web.xml设置的applicationContext.xml名字 String configFille = servletContext.getInitParameter("configFile"); //得到context对象 ApplicationContext context = new ClassPathXmlApplicationContext(configFille); servletContext.setAttribute(SPRING_CONTAINER_KEY,context); } @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { } }
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_4_0.xsd" version="4.0"> <context-param> <param-name>configFile</param-name> <!--设置xml名称--> <param-value>applicationContext.xml</param-value> </context-param> <listener> <!--绑定监听器类--> <listener-class>com.web.ApplicationContextInstantiateListener</listener-class> </listener> </web-app>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>druid加dbutils加spring查询所有</title> <script src="jq/jquery-3.4.1.js"></script> </head> <body> <div> <table> <tr> <th>编号</th> <th>姓名</th> <th>工资</th> </tr> <tbody id="tb1"> </tbody> </table> </div> </body> <script> window.onload = function (ev) { loadEmp(); } function loadEmp() { $.ajax({ method:"get", url:"/select", dataType:"json" }).done(function (employees) { var tr = ""; $.each(employees,function (index,emp) { tr +="<tr>"; tr +="<td>"+emp.id+"</td>"; tr +="<td>"+emp.username+"</td>"; tr +="<td>"+emp.salary+"</td>"; tr +="</tr>"; }) $("#tb1").html(tr); }).fail(function () { alert("请求失败") }) } </script> </html>
1、mybatis依赖和mybatis-spring依赖是必须要添加的。
2、dao接口使用注解Select注入SQL语句。
3、使用MapperFactoryBean类创建出特殊的接口bean。