使用idea搭建一个简单的SSM框架:(3)配置spring+mybatis

1 配置spring和mybatis整合文件

spring和mybatis整合分为三个步骤:(1)配置数据库,(2)配置SqlSessionFactoryBean (来自mybatis-spring),(3)配置MapperScannerConfigurer,该配置就我们通过接口定义的方法,就是mybatis的xml对应的namespace对应的接口。

在配置之前先要新建dao文件夹,用来放置接口。

  1. 在resources文件夹下新建mybatis-config.xml来放置mybatis基本配置。
  2. 在resources文件夹下新建mapper文件夹来放置mybatis的xml文件。
  3. 在resources/spring下新建spring-dao-config.xml来放置整合配置。

mybatis-config.xml

复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!--配置全局属性-->
    <settings>
        <!--使用jdbc的getGeneratedKeys获取自增的主键值-->
        <setting name="useGeneratedKeys" value="true"/>
        <!--使用列标签代替列名-->
        <setting name="useColumnLabel" value="true"/>
        <!--是否开启自动驼峰命名规则-->
        <setting name="mapUnderscoreToCamelCase" value="true "/>
    </settings>
</configuration>
复制代码

jdbc.properties

复制代码
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/someoneisyou?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
#定义初始连接数
initialSize=0
#定义最大连接数
maxPoolSize=30
#最小连接数
minPoolSize=10
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
复制代码

spring-dao-config.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" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <!--(1)配置数据库-->
    <!--加载数据库连接配置-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--c3po最重要的api-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="user" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <!--c3po连接处私有属性-->
        <!--最大连接数-->
        <property name="maxPoolSize" value="${maxPoolSize}"/>
        <!--最小连接数-->
        <property name="minPoolSize" value="${minPoolSize}"/>
        <!--关闭连接后不自动commint-->
        <property name="autoCommitOnClose" value="false"/>
        <!--表示当连接数到达最大时,超时时间-->
        <property name="checkoutTimeout" value="1000"/>
        <!--重试次数-->
        <property name="acquireRetryAttempts" value="2"/>
    </bean>
    <!--(2)配置SqlSessionFactoryBean 来自mybatis-spring-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--数据源-->
        <property name="dataSource" ref="dataSource"/>
        <!--配置mybatis的全局配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--扫描model包,-->
        <property name="typeAliasesPackage" value="cn.demo.model"/>
        <!--扫描sql配置文件-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <!--扫描dao接口,动态实现接口,并且注入到spring容器中
    就是xml配置文件中namespace中的接口
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!--给出要扫描的包的地址-->
        <property name="basePackage" value="cn.demo.dao"/>
    </bean>
</beans>
复制代码

 

typeAliasesPackage是用来放置实体类所在的包。

经过上面的配置就已经将spring和mybatis整合到一起了

 

2 新建表进行测试

新建一张简单的表

CREATE TABLE `account` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `money` double DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

 

新建该表的实例

复制代码
package cn.demo.model;

/**
 * Created by Administrator on 2017/3/22.
 */
public class Account {

    private Integer id;

    private String name;

    private Long money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getMoney() {
        return money;
    }

    public void setMoney(Long money) {
        this.money = money;
    }

  @Override
  public String toString() {
    return "Account{" +
            "id=" + id +
            ", name='" + name + '\'' +
            ", money=" + money +
            '}';
  }
}
复制代码

 

新建AccountDao接口

复制代码
package cn.demo.dao;

import cn.demo.model.Account;

import java.util.List;

/**
 * Created by Administrator on 2017/3/22.
 */
public interface AccountDao {

    public List<Account> getAllAccount();

}
复制代码

 

在resources下的mapper中新建AccountDao.xml

复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.demo.dao.AccountDao">
    <resultMap id="defuaresultMap" type="cn.demo.model.Account">
        <id column="id" property="id"></id>
        <result column="name" property="name"></result>
        <result column="money" property="money"></result>
    </resultMap>


    <!--于接口对应的方法-->
    <select id="getAllAccount" resultMap="defuaresultMap">
        SELECT
        id,
        name,
        money
        FROM account
    </select>

</mapper>
复制代码

 

在xml有几点需要注意:namespace中对应该接口地址,type是对应实体,其实这些都在配置文件中有配置过的,不能随意修改,如果不对会导致mybatis执行出错

<mapper namespace="cn.demo.dao.AccountDao">
<resultMap id="defuaresultMap" type="cn.demo.model.Account">

新建包cn.demo.service以及AccountService来测试配置是否正确

 

AccountService

复制代码
package cn.demo.service;

import cn.demo.dao.AccountDao;
import cn.demo.model.Account;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * Created by Administrator on 2017/3/22.
 */
public class AccountService {

    @Autowired
    private AccountDao accountDao;

    /**
     *
     * @return
     */
    public List<Account>getAllAccount(){
        List<Account> accountList=new ArrayList<Account>();
        accountList=accountDao.getAllAccount();
        return accountList;
    }

}
复制代码

 

 

写完Service就可以进行测试,测试使用junit。

在创建测试时要先新建一个test,并且在modules的sources中设置为测试类如下:

 

创建测试类的具体方法如下:在AccountService类中鼠标右击->选择Go To->点击Test->选择create new test

在这时要注意选择的测试方式JUnit4,如果没有需要下载插件

点击ok,idea会自动给我们创建测试类AccountServiceTest

测试类AccountServiceTest

复制代码
package cn.demo.service;

import cn.demo.dao.AccountDao;
import cn.demo.model.Account;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * Created by Administrator on 2017/3/22.
 */
@RunWith(SpringJUnit4ClassRunner.class)
//这个是用来加载写好的配置文件,传入的值是数组形式多个配置文件如下 {"····","·······"}
@ContextConfiguration({"classpath:spring/spring-dao-config.xml"})
public class AccountServiceTest {

    @Autowired
    private AccountDao accountDao;

    @Test
    public void getAllAccount() throws Exception {
        List<Account> accountList = accountDao.getAllAccount();
        System.out.println("accountList=" + accountList.toString());
    }

}
复制代码

 

点击测试:从中可以看出已经成功从数据库中查出数据,证明配置成功了

 

 

3 最后一步:配置service,添加事务,配置web.xml将所有的配置加载进去

到此就可以长出一口气了,重点查询数据库的配置已经完成,接下来就要配置service层添加事务。

  spring实现事务有三种方法:
  1. 编程式的事务管理
  2. 使用XML配置声明式的事务管理,基于tx/aop
  3. 使用注解配置声明式事务

至于我么现在选择最简单的方式第三种

在resources的spring下新建spring-service.xml

spring-service.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.1.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
         http://www.springframework.org/schema/task
         http://www.springframework.org/schema/task/spring-task-3.1.xsd">

    <!--开启自动扫描包-->
    <context:component-scan base-package="cn.demo.service"/>

    <!--事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--此处的dataSource报错是因为在本xml中没有定义,但是在dao的xml中已经定义过了,只要同时将两个文件加载到spring中就可以了
        原因是在spring容器中bean的id是唯一的
        -->
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 开启注解事务 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
复制代码

 

然后再次修改我们的service在方法名称上添加 @Transactional 的注解,就能完成事务的控制了,当然这是最简单的控制,想要具体了解的可以看Transactional 注解的源代码

    @Transactional
    public List<Account>getAllAccount(){
        List<Account> accountList=new ArrayList<Account>();
        accountList=accountDao.getAllAccount();
        return accountList;
    }

 

最后修改web.xml

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name>Archetype Created Web Application</display-name>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:spring/spring-dao-config.xml,
      classpath:spring/spring-service.xml
    </param-value>
  </context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
  <!-- 编码过滤器 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <async-supported>true</async-supported>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <servlet>
    <servlet-name>springMvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/spring-web.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>
复制代码

 

这部分就是我新添加的代码,用来加载spring-dao-config.xml,spring-service.xml
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:spring/spring-dao-config.xml,
      classpath:spring/spring-service.xml
    </param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

修改Demo1Controller
复制代码
package cn.demo.controller;

import cn.demo.model.Account;
import cn.demo.service.AccountService;
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 org.springframework.web.bind.annotation.RequestMethod;

import java.util.List;

/**
 * Created by Administrator on 2017/3/22.
 */
@Controller
public class Demo1Controller {

    @Autowired
    private AccountService accountService;


    /***
     * value表示在浏览器输入的地址如:http://localhost:8080/simple-demo/demo
     * method可以不写,默认为GET,当处理POST请求时必须要写method = RequestMethod.POST,否则找不到地址
     *
     * @return 返回的是页面的地址,在配置文件InternalResourceViewResolver中配置prefix和suffix相当于最后返回/WEB-INF/jsp/demo1.jsp
     */
    @RequestMapping(value = "/simple-demo/demo",method = RequestMethod.GET)
    public String demo1View(Model model){
        List<Account> accountList= accountService.getAllAccount();
        model.addAttribute("accountList",accountList);
        return "demo1";
    }
}
复制代码

 

最后重启jetty runner访问 http://localhost:8080/simple-demo/demo 



至此所有的配置完成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值