Spring+Mybatis+Velocity整合(3):整合Mybatis

Stella981
• 阅读 582

正式开始配置关键内容,这是硬货 
1、新建spring配置文件,起名为 applicationContext.xml,放在src/main/resources/spring目录下。 
内容如下:

<?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:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!--开始配置-->
</beans>

2、web.xml文件配置

<context-param>
    <param-name>contextConfigLocation</param-name>
     <!-- 上面配置的spring配置文件的路径,区分大小写  -->
    <param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

加入这个用来在启动web容器时,读取spring配置

3.新建数据源的配置文件datasource.properties放在src/main/resources目录下:

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/user?characterEncoding=utf-8
username=root
password=1234

4.配置一个duird数据源,在applicationContext.xml中加入:

    <!--开始配置-->

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="classpath:datasource.properties" />
    </bean>

    <!-- 配置数据源 -->
    <bean id="ds"  class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url"             value="${url}"/>
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="username"        value="${username}"/>
        <property name="password"        value="${password}"/>
    </bean>

5.配置Mybatis

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath*:mappers/*Mapper.xml"></property>
    </bean>

    <bean name="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.jczj123.Test3.dao"/>
    </bean>

6.配置就这么多,下面是代码

model下新建User实体类

package com.jczj123.Test3.model;

/**
 * Created by wangkai on 2017/7/9.
 */
public class User {

    private Integer id;

    private String username;

    private String password;

    public User(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public Integer getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

在dao下新建一个UserMapper

package com.jczj123.Test3.dao;

import com.jczj123.Test3.model.User;

import java.util.List;

/**
 * Created by wangkai on 2017/7/9.
 */
public interface UserMapper {

    User selectById(int id);

    List<User> selectAll();

}

在src/main/resources下新建目录mappers

新建UserMapper.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="com.jczj123.Test3.dao.UserMapper" >
    <resultMap id="BaseResultMap" type="com.jczj123.Test3.model.User" >
        <constructor >
            <idArg column="id" jdbcType="INTEGER" javaType="java.lang.Integer" />
            <arg column="username" jdbcType="VARCHAR" javaType="java.lang.String" />
            <arg column="password" jdbcType="VARCHAR" javaType="java.lang.String" />
        </constructor>
    </resultMap>
    <sql id="Base_Column_List" >
        id, username, password
    </sql>
    <select id="selectById" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select
        <include refid="Base_Column_List" />
        from user
        where id = #{id,jdbcType=INTEGER}
    </select>

    <select id="selectAll" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from user
    </select>

</mapper>

service包下新建IUserService接口

package com.jczj123.Test3.service;

import com.jczj123.Test3.model.User;

import java.util.List;

/**
 * Created by wangkai on 2017/7/9.
 */
public interface IUserService {

    User findById(int id);

    List<User> findAll();

}

service包下新建子包impl

新建实现类

UserServiceImpl

package com.jczj123.Test3.service.impl;

import com.jczj123.Test3.dao.UserMapper;
import com.jczj123.Test3.model.User;
import com.jczj123.Test3.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by wangkai on 2017/7/9.
 */
@Service(value = "userService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    public User findById(int id) {
        return userMapper.selectById(id);
    }

    public List<User> findAll() {
        return userMapper.selectAll();
    }
}

controller下新建一个UserController

package com.jczj123.Test3.controller;

import com.jczj123.Test3.model.User;
import com.jczj123.Test3.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * Created by wangkai on 2017/7/9.
 */
@Controller
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/list.do")
    public String doGet(ModelMap modelMap) {
        List<User> userList = userService.findAll();

        modelMap.addAttribute("users", userList);
        return "userList";
    }
}

velocity下新建userList.vm文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户列表</title>
</head>
<body>
    <table border="1">
        <tr>
            <th>用户id</th>
            <th>用户名</th>
            <th>密码</th>
        </tr>
        #foreach($user in $users)
            <tr>
                <td>$user.id</td>
                <td>$user.username</td>
                <td>$user.password</td>
            </tr>
        #end
    </table>
</body>
</html>

启动tomcat服务器,浏览器访问:

http://localhost:8088/list.do

就可以看到:

Spring+Mybatis+Velocity整合(3):整合Mybatis

表示成功了

代码托管在码云上,地址是:

http://git.oschina.net/nicekk/spring-mybatis-simple

欢迎访问

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
待兔 待兔
2个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Redis在SSM框架的使用(三)
Spring整合springdataredis1、springredis.xml<?xmlversion"1.0"encoding"UTF8"?<beansxmlns"http://www.springframework.org/schema/beans"xmlns:xsi"http
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
8个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这