码迷,mamicode.com
首页 > 编程语言 > 详细

mybatis spring 全注解配置

时间:2019-01-02 20:46:34      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:model   frame   ann   连接   ase   ext   整合   pen   min   

pom引入jar包
        <!-- mybatis jar start -->
        <!-- mybatis核心包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>
        <!-- mybatis/spring包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.2</version>
        </dependency>

spring配置

    <!--导入外部配置文件  -->
    <context:property-placeholder location="classpath:jdbc.properties"
        ignore-unresolvable="true"/>

    <!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
    <!-- spring注解扫描包 -->
    <context:component-scan base-package="com.services" >
       <context:exclude-filter type="annotation"
            expression="org.springframework.stereotype.Controller" />
    </context:component-scan>

    <!-- 数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"  
        destroy-method="close">
        <property name="driverClassName" value="${jdbc.mysql.driverClassName}" />
        <property name="url" value="${jdbc.mysql.url}" />
        <property name="username" value="${jdbc.mysql.username}" />
        <property name="password" value="${jdbc.mysql.password}" />
        <!-- 初始化连接大小 -->
        <property name="initialSize" value="${initialSize}"></property>
        <!-- 连接池最大数量 -->
        <property name="maxActive" value="${maxActive}"></property>
        <!-- 连接池最大空闲 -->
        <property name="maxIdle" value="${maxIdle}"></property>
        <!-- 连接池最小空闲 -->
        <property name="minIdle" value="${minIdle}"></property>
        <!-- 获取连接最大等待时间 -->
        <property name="maxWait" value="${maxWait}"></property>
        <!-- 禁止默认自动提交 -->
        <property name="defaultAutoCommit">
            <value>false</value>
        </property>
        <!-- 开启测试连接 -->
        <property name="testWhileIdle">
                <value>true</value>
        </property>
        <property name="testOnBorrow">
                <value>true</value>
        </property>
        <property name="validationQuery">
                   <value>select 1 from dual</value>
        </property>
        <property name="timeBetweenEvictionRunsMillis">
                   <value>300000</value>
        </property>
        <property name="numTestsPerEvictionRun">
                   <value>3</value>
        </property>
        <property name="minEvictableIdleTimeMillis">
                   <value>600000</value>
        </property>
    </bean>

    <!-- spring和MyBatis整合 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <!-- mybatis-config.xml -->
        <property name="configLocation" value="classpath:spring/mybatis-config.xml"/>
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.daos" />
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
    </bean>

    <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 注解事务扫描 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>

jdbc.properties 数据库配置文件

###mysql表
jdbc.mysql.driverClassName=com.mysql.jdbc.Driver
#[ 测试用 ]
jdbc.mysql.url=jdbc:mysql://10.143.131.52:3306/test
jdbc.mysql.username=test
jdbc.mysql.password=test

#初始化连接大小
initialSize=3
#连接池最大数量
maxActive=50
#连接池最大空闲
maxIdle=10
#连接池最小空闲
minIdle=0
#获取连接最大等待时间
maxWait=-1

使用方法

例:查询

实体类

package com.dto;

public class TestDTO {

    private String id;
    private String name;
    private int age;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }

}

DAO层

package com.daos;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import com.dto.TestDTO;

@Mapper
public interface TestDAO {

    @Select("<script> " +
            "select " +
            "t.ID  as id " +
            ",t.NAME  as name " +
            ",t.AGE as age " +

            "from " + 
            "${tablename} t " +
            "where " +
            "t.age in " +
            "<foreach item=‘item‘ index=‘index‘ collection=‘ages‘ open=‘(‘ separator=‘,‘ close=‘)‘> " +
            "#{item} " +
            "</foreach> " +
            "</script> "
            )
    List<TestDTO> list(@Param("tablename")String tablename, @Param("ages")List<int> ages);
}

service层接口

package com.services;

import java.util.List;

import com.dto.TestDTO;

public interface TestService {

    /**
     * 信息
     * @param 
     */
    public List<TestDTO> list(String tablename, List<int> ages);

}

service层实现

package com.services.impl;

import java.util.List;

import com.daos.TestDAO;
import com.dto.TestDTO;
import com.services.TestService;

@Service
public class TestService implements TestService{

    @Autowired
    private TestDAO testDAO;

    /**
     * 信息
     * @param 
     */
    public List<TestDTO> list(String tablename, List<int> ages){
      try {
            return testDAO.list(tablename, ages);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ArrayList<TestDTO>();
    }

}

controller层

package com.web;

import java.util.ArrayList;
import java.util.List;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.daos.TestDAO;
import com.dto.TestDTO;
import com.services.TestService;

/**
 * @功能 处理相关请求
 * @author zjw
 * 
 */
@Controller
@RequestMapping("/test")
public class TestController extends BaseController {
    private static final Logger log = LoggerFactory
            .getLogger(TestController.class);

    @Autowired
    private TestService testServiceImpl;

    /************************************* 任务管理 **********************************/
    /**
     * @functional 页面跳转
     * @param model
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/test.do")
    public String test(Model model, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        List<int> ageList = new ArrayList<>();
        mobileList.add(80);
        List<TestDTO> tests = testServiceImpl.list("t_test", ageList);
        System.out.println("tests:"+tests+":"+tests.size());
        return "/view/test/listTest";
    }

}

mybatis spring 全注解配置

标签:model   frame   ann   连接   ase   ext   整合   pen   min   

原文地址:http://blog.51cto.com/jtech/2338035

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!