spring 4.1.7 + MyBatis 3.3

正式开始配置关键内容,这是硬货

一. 新建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>

二. 找到web.xml文件

放入以下内容,用来读取spring的配置

<!-- spring的监听以及配置文件加载信息  -->
    <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>

三. 继续配置applicationContext.xml

1. 放入以下内容,都有注释,不多解释了:

 <!-- 开启IOC扫描 -->
    <context:component-scan base-package="com.bench.app.ebuy"/>

    <!-- 开启注解扫描 -->
    <mvc:annotation-driven/>

四.配置spring的数据源

新建连接数据库的配置文件jdbc.properties放在src/main/resources下

内容如下(我用的mysql数据库)

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/db_ebuy
username=root
password=admin
  1. 在applicationContext.xml中放入以下内容
 <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations" value="classpath:jdbc.properties" />
    </bean>

    <!-- 配置数据源 -->
    <bean id="ds"  class="org.apache.commons.dbcp.BasicDataSource"  destroy-method="close">
        <property name="url"             value="${url}"/>
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="username"        value="${username}"/>
        <property name="password"        value="${password}"/>
    </bean>

这样spring的数据源就配置好了

五、配置MyBatis

在src/main/resources下新建文件夹mybatis,在其下新建mybatis-config.xml

内容如下(这里不用配置数据源了,都在applicationContext.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>
    <typeAliases>
        <typeAlias alias="User" type="com.bench.app.ebuy.model.User"/>
    </typeAliases>
    <mappers>
        <mapper resource="com/bench/app/ebuy/mappers/UserMapper.xml" />
    </mappers>
</configuration>

在applicationContext.xml中加入以下内容:

<!-- 配置SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
      <property name="dataSource" ref="ds" />
      <!--  MyBatis配置-->
      <property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
    </bean>

主要配置MyBatis的SqlSessionFactory,这是MyBatis的核心类之一,用来进行数据库操作

这里我们是要以注解的方式来识别MyBatis的Mapper接口,新建一个包 annotation

在下面新建一个接口,

package com.bench.app.ebuy.annotation;

/**
 * 自定义的Mybatis注解,用来描述Mybatis接口,
 * 目的是让MapperScannerConfigurer扫描到该接口
 * @author
 *
 */
public @interface MybatisRepository {

}

并且在applicationContext.xml中配置这个注解

<!-- 配置MyBatis注解 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
       <!-- 指定MapperScannerConfigurer要扫描的包 -->
       <property name="basePackage" value="com.bench.app.ebuy.dao" />
       <!-- 指定MapperScannerConfigurer要扫描的注解,该注解需要自定义。 -->
       <property name="annotationClass"  value="com.bench.app.ebuy.annotation.MybatisRepository"/>
    </bean>

这样,就都配置好了,

下面写测试用例:

新建一个包,model:

新建User类

package com.bench.app.ebuy.model;

/**
 * 用户
 * @author
 *
 */
public class User2 {

    /**
     * 主键,id
     */
    private long id ;

    /**
     * 用户名
     */
    private String userName;

    public long getId() {
        return id;
    }

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

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

}

新建一个包mapper,这里面放mapper接口,如:

新建一个UserMapper接口

package com.bench.app.ebuy.dao;

import com.bench.app.ebuy.annotation.MybatisRepository;
import com.bench.app.ebuy.model.User;

/**
 * 用户操作
 * @author
 *
 */
@MybatisRepository
public interface UserMapper {

    /**
     * 新增一个用户
     * @param user
     */
    public void add(User user);
}

注意,需要加上自定义的注解

新建一个包mappers,这里面放sql的配置文件

新建一个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.bench.app.ebuy.dao.UserMapper">

    <insert id="add" parameterType="User"  >
        insert into t_user (status,username) values(#{status},#{userName})
    </insert>

</mapper> 

注意一下这个sql,能用#号的地方 绝不用¥,因为#可以自动加引号,并且#可以防止sql注入,而¥不可以

新建包service,服务层,

新建类

package com.bench.app.ebuy.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.bench.app.ebuy.dao.UserMapper;
import com.bench.app.ebuy.model.User;

/**
 * 用户服务
 * @author
 *
 */
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    public void add(User user) {

        userMapper.add(user);
    }

}

新建一个包controller,新建类:

package com.bench.app.ebuy.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.bench.app.ebuy.model.User;
import com.bench.app.ebuy.service.UserService;

/**
 * 测试控制器
 * @author
 *
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/add.do")
    public String doGet() {
        User user = new User();
        user.setStatus(1);
        user.setUserName("wangkai");
        userService.add(user);
        return "redirect:index.html";
    }
}

这里重定向到原来的网页,如果返回值为void,会报错

修改index.html的内容为:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <a href="add.do">添加一条数据</a>
</body>
</html>

放入tomcat中执行,会成功向数据库中插入一条数据(数据库的表自己建了)

web项目环境搭建(3):搭建Spring+MyBatis的更多相关文章

  1. web项目中加入struts2、spring的支持,并整合两者

    Web项目中加入struts2 的支持 在lib下加入strut2的jar包 2. 在web.xml中添加配置 <filter> <filter-name>struts2< ...

  2. 0028ssm环境搭建(springmvc+spring+mybatis)

    spring整合springmvc和mybatis主要分为如下几个步骤: 1.spring环境搭建 2.springmvc环境搭建 3.spring整合springmvc 4.spring整合myba ...

  3. Eclipse 的 Java Web 项目环境搭建

    从svn上拉取下来Eclipse的项目 IntelliJ IDEA自动识别到可编译的 src 类目录 Java Web 项目 html(一般命名为:WebRoot) 是整个项目输出的根目录. WEB- ...

  4. SSM框架开发web项目系列(五) Spring集成MyBatis

    前言 在前面的MyBatis部分内容中,我们已经可以独立的基于MyBatis构建一个数据库访问层应用,但是在实际的项目开发中,我们的程序不会这么简单,层次也更加复杂,除了这里说到的持久层,还有业务逻辑 ...

  5. 使用 IDEA 创建 Maven Web 项目 (二)- 搭建 WEB 项目框架

    转为 Java Web 项目 将上一节中创建的 Maven 项目调整为 WEB 项目结构,步骤如下: 在 main 目录下,添加 webapp 目录. 在 webapp 目录下,添加 WEB-INF ...

  6. maven的java web项目启动找不到Spring ContextLoaderListener的解决办法

    用maven搭建的java web项目,上传到git仓库后,当同事clone下来项目,部署到tomcat运行时,就报了如下错误,即启动web项目时,加载web.xml文件,找不到spring的监听器, ...

  7. sass创建web项目环境步骤

    1)npm创建web前端项目环境步骤 1.新建文件夹,在该文件下进入cmd控制台2.输入命令 npm init 回车3.name:名字只支持小写,不支持大写,将大写的名字改为小写即可4.version ...

  8. 项目SpringMVC+Spring+Mybatis 整合环境搭建(2)-> 测试Spring+Mybatis 环境

    测试前期准备 第一步:创建easybuy数据库,设置utf-8格式 第二步:创建表test_tb CREATE TABLE `test_tb` ( `id` int(11) NOT NULL AUTO ...

  9. web项目环境搭建(2):整合SpringMVC+velocity

    velocity是一个基于java的模板引擎.velocity应用于web开发时,前端设计人员可以只关注页面的显示效果,而java程序人员只关注业务逻辑代码.velocity将java代码从web页面 ...

随机推荐

  1. JS简易时钟

    HTML <div id="clock"> <span></span>:<span></span>:<span&g ...

  2. Javascript闭包与作用域

    摘自开源中国 闭包和作用域是js中比较重要的知识,自己理解起来也有一定的难度 1.Javascript的作用域是函数作用域而非块级作用域 ? 1 2 3 4 5 6 7 8 9 10 11 12 // ...

  3. C语言学习笔记--类型定义&联合

    一.类型定义 C语言自定义数据类型 (typedef) C语言提供一个叫做typedef的功能来声明一个已有的数据类型的新名字. typedef int Length; 使得Length成为int类型 ...

  4. Delphi会自动初始化全局变量和类成员变量,但不初始化局部变量

    If you don't explicitly initialize a global variable, the compiler initializes it to 0. Object insta ...

  5. org.elasticsearch.bootstrap : JNA not found. native methods will be disabled

    在pom.xml中添加以下依赖,解决elasticsearch的WARN: <dependency> <groupId>com.sun.jna</groupId> ...

  6. UVALive 4394 String painter

    这题搞了很久很久..弄得我都不想放上来了,但是想了想还是写上来吧,万一以后忘了怎么做了,又得搞很久很久了.题目是要求把一个字符串变成另外一个,每次可以选择一段字符串变成同一个字符,问最少用变多少次.本 ...

  7. Android子线程更新主界面

    学习什么的还是要真正的有应用,有需求才能在最短的时间里面牢牢掌握一项技术. 今天就是这样的,产品一个需求下来,十万火急啊.然后之前只稍稍接触过,只能硬着头皮上了.最后牢牢地掌握了最简单的Handler ...

  8. 剑指offer---3

    1.反转单链表,输入链表的头节点,输出该链表,并输出反转后的头节点 这个题目不用再说了,写过N边了 SLnode reverse(SLnode head) { SLnode reverse_head ...

  9. Sublime text 3 格式化HTML/css/js/json代码 插件

    JsFormat: 这里下载这插件包 https://github.com/jdc0589/JsFormat ,点油下角的zip就能下载 插件包放到sublime安装目录的Data\Packages目 ...

  10. 【转】两种方法教你在Ubuntu下轻松关闭触摸板(TinkPad)

    Ubuntu是一个以桌面应用为主的Linux操作系统,所以在使用时我经常的触碰到触摸板,这样会造成我们一些的麻烦,所以要如何的关闭触摸板呢?我们一起来看看吧!   Ubuntu下如何关闭触摸板(Tin ...