spring-mvc框架学习(三)

上一章完成了基本的spring  web 项目,后边有很多可以添加完善的地方,就又研究了下 spring+maven+mybatis 实现与数据库的交互,其中额外涉及了 zk、dubbo 等内容

主要工作就是
1、引入 mybatis 的 jar 包提供调用依赖
2、搭建 mysql 数据库,创建一个测试库表
3、编写代码实现对 mysql 的调用,其中又涉及spring-mvc中的 controller+dao+mapping 映射思想,将代码拆成了多个部分
4、由于我司内部调用大量采用 dubbo协议,故又将 dubbo服务引入工程中,通过 service 将服务暴露于为 dubbo服务,将查询数据库的方法实现前台 url 调用,也可直接通过 dubbo 服务调用
涉及的代码及配置文件较多,下边上学习代码:
1、在 src_main_resource 下的配置文件,主要是配置 mybatis-jdbc连接,以及日志设置,多个配置文件 resource.zip
2、代码目录下,新增如下代码文件,其中新的控制器入口为 UserController,实现了从数据库根据 id 查询详情的功能


3、各文件代码如下

UserController.java

package com.springmvc.controller;

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

import org.springframework.stereotype.Controller;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.springmvc.domain.User;
import com.springmvc.service.IUserService;

@Controller
@RequestMapping(value = "/user")
@ContextConfiguration(locations = { "classpath:spring-mybatis.xml" })
public class UserController {
	@Resource
	private IUserService userService;

	@RequestMapping(value = "/showUser")
	public String toIndex(HttpServletRequest request, Model model) {

		int userId = Integer.parseInt(request.getParameter("id"));
		User user = this.userService.getUserById(userId);
		model.addAttribute("user", user);
		return "showUser";
	}
}

IUserDao.java

package com.springmvc.domain;

public class User {
	private Integer id;

	private String userName;

	private String password;

	private Integer age;

	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 == null ? null : userName.trim();
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password == null ? null : password.trim();
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}
}

User.java 其实这部分实现了多个查询功能,代码中仅调用了第一个根据 id 查询

package com.springmvc.dao;

import com.springmvc.domain.User;

public interface IUserDao {
	int deleteByPrimaryKey(Integer id);

	int insert(User record);

	int insertSelective(User record);

	User selectByPrimaryKey(Integer id);

	int updateByPrimaryKeySelective(User record);

	int updateByPrimaryKey(User record);
}

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.springmvc.dao.IUserDao" >

  <resultMap id="BaseResultMap" type="com.springmvc.domain.User" >

    <id column="id" property="id" jdbcType="INTEGER" />

    <result column="user_name" property="userName" jdbcType="VARCHAR" />

    <result column="password" property="password" jdbcType="VARCHAR" />

    <result column="age" property="age" jdbcType="INTEGER" />

  </resultMap>

  <sql id="Base_Column_List" >

    id, user_name, password, age

  </sql>

  <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="com.springmvc.domain.User" >

    select 

    <include refid="Base_Column_List" />

    from user_t

    where id = #{id,jdbcType=INTEGER}

  </select>

  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >

    delete from user_t

    where id = #{id,jdbcType=INTEGER}

  </delete>

  <insert id="insert" parameterType="com.springmvc.domain.User" >

    insert into user_t (id, user_name, password, 

      age)

    values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR}, 

      #{age,jdbcType=INTEGER})

  </insert>

  <insert id="insertSelective" parameterType="com.springmvc.domain.User" >

    insert into user_t

    <trim prefix="(" suffix=")" suffixOverrides="," >

      <if test="id != null" >

        id,

      </if>

      <if test="userName != null" >

        user_name,

      </if>

      <if test="password != null" >

        password,

      </if>

      <if test="age != null" >

        age,

      </if>

    </trim>

    <trim prefix="values (" suffix=")" suffixOverrides="," >

      <if test="id != null" >

        #{id,jdbcType=INTEGER},

      </if>

      <if test="userName != null" >

        #{userName,jdbcType=VARCHAR},

      </if>

      <if test="password != null" >

        #{password,jdbcType=VARCHAR},

      </if>

      <if test="age != null" >

        #{age,jdbcType=INTEGER},

      </if>

    </trim>

  </insert>

  <update id="updateByPrimaryKeySelective" parameterType="com.springmvc.domain.User" >

    update user_t

    <set >

      <if test="userName != null" >

        user_name = #{userName,jdbcType=VARCHAR},

      </if>

      <if test="password != null" >

        password = #{password,jdbcType=VARCHAR},

      </if>

      <if test="age != null" >

        age = #{age,jdbcType=INTEGER},

      </if>

    </set>

    where id = #{id,jdbcType=INTEGER}

  </update>

  <update id="updateByPrimaryKey" parameterType="com.springmvc.domain.User" >

    update user_t

    set user_name = #{userName,jdbcType=VARCHAR},

      password = #{password,jdbcType=VARCHAR},

      age = #{age,jdbcType=INTEGER}

    where id = #{id,jdbcType=INTEGER}

  </update>

</mapper>


IUserService.java

package com.springmvc.service;

import com.springmvc.domain.User;

public interface IUserService {
	public User getUserById(int userId);
}


UserServiceImpl.java   service 的继承实现类

package com.springmvc.service.impl;

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

import com.springmvc.dao.IUserDao;
import com.springmvc.domain.User;
import com.springmvc.service.IUserService;

@Service("userService")
public class UserServiceImpl implements IUserService {
	@Autowired
	private IUserDao userDao; // 注入dao

	@Override
	public User getUserById(int userId) {

		// TODO Auto-generated method stub
		return this.userDao.selectByPrimaryKey(userId);
	}

}

3、最后在view目录下新建showUser.jsp文件,展示结果

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

 姓名:${user.userName}<br>

 年龄:${user.age}

</body>

</html>

4、最终结果,附数据库原数据

相关阅读:spring-mvc框架学习(一)

spring-mvc框架学习(二)


本文来自网易实践者社区,经作者李亚松授权发布。