druid + mybatis-spring使用註解方式整合

一、準備須要的maven依賴

<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裏面的東西,因此須要導入依賴html

導入了mybatis-spring依賴也仍是須要mybatis依賴的。java

依賴版本以下:mysql

<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(按需求增長或減小,不是必定的)jquery

給每一個模塊的pom.xml文件添加對應須要的依賴。web

三、模塊操做

3-1 編寫entity模塊

將須要的實體類編寫,添加相應的屬性,getter(),setter(),toString()....方法。ajax

3-2 編寫util模塊

ApplicationContextHolder類:spring

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。sql

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接口:apache

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(); }

3-4 編寫service模塊

EmpService接口:json

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>

四、知識點總結:

一、mybatis依賴和mybatis-spring依賴是必需要添加的。

二、dao接口使用註解Select注入SQL語句。

三、使用MapperFactoryBean類建立出特殊的接口bean。

相關文章
相關標籤/搜索