mybatis+spring的TODO小项目记录(八)整合spring和mybatis

来源:互联网 发布:在mac上用win to go 编辑:程序博客网 时间:2024/06/06 04:37

前面分别介绍了mybatis和spring的使用,接下来就开始整合这两个框架,并在最后实现一个用户登录功能进行测试。

整合mybatis和spring

在之前使用mybatis时,我们单独使用了一个配置文件mybatis-config.xml进行mybatis的配置,然后使用SqlSessionFactoryBuilder从文件中读取配置,并构建SqlSessionFactory

Spring的两大核心之一是依赖注入,因此在整合了Spring之后,我们就可以在applicationContext.xml中设置相应的bean,让spring进行依赖注入。

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"       xmlns:context="http://www.springframework.org/schema/context"       xsi:schemaLocation="http://www.springframework.org/schema/beans       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">    <!-- 引入数据库配置文件 -->    <bean id="dbProperties" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">        <property name="location" value="classpath:db.properties"></property>    </bean>    <!--设置数据源-->    <bean id="dataSource" destroy-method="close"          class="org.apache.commons.dbcp2.BasicDataSource">        <property name="driverClassName" value="${driver}"></property>        <property name="url" value="${url}"></property>        <property name="username" value="${username}"></property>        <property name="password" value="${password}"></property>        <!-- 初始化连接大小 -->        <property name="initialSize" value="${initialSize}"></property>        <!--&lt;!&ndash; 连接池最大数量 &ndash;&gt;-->        <!--<property name="maxActive" value="${maxActive}"></property>-->        <!-- 连接池最大空闲 -->        <property name="maxIdle" value="${maxIdle}"></property>        <!-- 连接池最小空闲 -->        <property name="minIdle" value="${minIdle}"></property>        <!--&lt;!&ndash; 获取连接最大等待时间 &ndash;&gt;-->        <!--<property name="maxWait" value="${maxWait}"></property>-->    </bean>    <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 -->    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <!-- 给映射的类配置别名 -->        <!-- 默认的别名是model类的首字母小写 -->        <!-- 如:UserXxx实体类。别名为:userXxx-->        <property name="typeAliasesPackage" value="com.loveqh.todo.pojo" />        <!-- 自动扫描mybatis的mapping.xml文件 -->        <property name="mapperLocations" value="classpath:mybatis-mapper/*.xml"></property>    </bean>    <!-- DAO接口所在包名,Spring会自动查找其下的类 -->    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">        <property name="basePackage" value="com.loveqh.todo.dao" />        <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>    <!-- 设置自动扫描 -->    <context:annotation-config></context:annotation-config>    <context:component-scan base-package="com.loveqh.todo"></context:component-scan></beans>

整合测试

在整合了mybatis和spring之后,我们可以首先使用junit测试是否成功。

项目中代码分为以下几个包:

  • com.loveqh.todo.controller: 控制器(MVC中的C)
  • com.loveqh.todo.service:处理业务逻辑的接口
  • com.loveqh.todo.service.impl:业务逻辑接口的实现
  • com.loveqh.todo.dao:数据库逻辑实现
  • com.loveqh.todo.pojo:简单java对象
  • com.loveqh.todo.util:公共的工具类
  • com.loveqh.todo.test:单元测试的类

我们以通过用户id获得用户对象的case为例,进行整合测试。

在UserDao接口中,定义相应方法:

public interface UserDao {    User findUserById(int id);}

相应地,在userMapper.xml中,增加对应的sql语句映射:

    <select id="findUserById" resultMap="userResultMap" parameterType="int">        select * from user where id=#{value}    </select>

接下来,在UserService接口中增加该业务逻辑方法:

public interface UserService {    User getUserById(int id);}

并在UserServiceImpl类中进行实现:

@Servicepublic class UserServiceImpl implements UserService {    @Resource    private UserDao userDao;    public User getUserById(int id) {        return userDao.findUserById(id);    }}

在UserServiceImpl类中使用了@Service来标注它是一个业务层组件,使用了@Resource(或@Autowired)进行相应bean的装配。

最后,在UserTest类中进行测试:

//表示继承了SpringJUnit4ClassRunner类@RunWith(SpringJUnit4ClassRunner.class)     //Spring整合JUnit4测试时,使用该注解引入多个配置文件@ContextConfiguration(locations = {"classpath:applicationContext.xml"})public class UserTest {    @Resource      //@Autowired    private UserService userService;    @Test    public void findUserById() {        int id = 1;        System.out.println(userService);        User user = userService.getUserById(id);        System.out.println(user);        Assert.assertNotNull(user);        Assert.assertEquals(user.getId(), id);    }}

运行测试,就可以看到绿色的成功提示了。

登录功能实现

首先编写一个简单的登录界面:

<%--  Created by IntelliJ IDEA.  User: WL  Date: 2017-05-02  Time: 15:32  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>登录</title></head><body>    <form action="/user/login" method="get">        <label for="username">用户名:</label>        <input type="text" name="username" id="username">        <label for="password">密  码:</label>        <input type="password" name="password" id="password">        <button type="submit">登录</button>    </form></body></html>

接下来,编写相应的控制器LoginController相应登录的请求:

/** * Created by WL on 2017-04-27. */@Controller@RequestMapping(value = "/user")public class LoginController {    @Resource    private UserService userService;    @RequestMapping(value = "/loginPage", method = RequestMethod.GET)    public String loginPage() {        return "login";    }    @RequestMapping(value = "/login", method = RequestMethod.GET)    public String index(@RequestParam("username") String username,                              @RequestParam("password") String password,                              Model model) {        boolean flag = userService.login(username, password);        if(flag) {            User user = userService.getUserByName(username);            model.addAttribute(user);            return "user";        } else {            return "fail";        }    }    @RequestMapping(value = "info", method = RequestMethod.GET)    public @ResponseBody String list() {        return userService.getUserById(1).toString();    }}

在这里,使用@Controller标注它是一个控制层组件,并使用@RequestMapping来配置处理的请求路径,@RequestParam(“username”)用来获取请求的参数。

最后成功登陆后返回的是user.jsp页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>TODO</title></head><body>    欢迎您,${user.getName()}!    您的个人信息如下:    ${user}</body></html>

在这里,我们简单的直接打印用户进行测试,最终看到了当前用户的全部信息。到此,简单的登录功能已经完成!

0 0