初識spring mvc+mybatis

52105 ワード

背景
この間、別のプロジェクトチームに行ってspring mvc+mybatisのプロジェクトを作りました.私はこれまでこの方面の技術(T_T)に触れたことがないので、最初はいくつかの困難に遭遇しました.ここで自分の間違いを記録します.
珍しい点
xmlを使用してデータベースを構成するDAOメソッド
以前はhibernateでデータベースを構成するときに注釈を使用していましたが、削除変更はDAOレイヤに置かれていましたが、このプロジェクトのmybatisはxmlで削除変更を書く方法で、普通のsql文に似ています.xmlファイルにselect、insert、update、deleteメソッドがあります.例を挙げてみましょう.



<mapper namespace="com.myProject.dao.ShopMapper">
    
    <resultMap id="BaseResultMap" type="com.myProject.model.Shop">
        
        <id column="ID" property="id" jdbcType="INTEGER" />
        <result column="shopAddr" property="shopAddr" jdbcType="VARCHAR" />
        <result column="shopIcon" property="shopIcon" jdbcType="VARCHAR" />
        <result column="shopName" property="shopName" jdbcType="VARCHAR" />
        <result column="shopStatus" property="shopStatus" jdbcType="INTEGER" />
        <result column="userId" property="userId" jdbcType="INTEGER" />
    resultMap>
    
    <sql id="Base_Column_List">
        ID, shopAddr, shopIcon, shopName, shopStatus, userId
    sql>
    
    <select id="selectByPrimaryKey" resultMap="BaseResultMap"
        parameterType="java.lang.Integer">
        select
        <include refid="Base_Column_List" />
        from shop
        where ID = #{id,jdbcType=INTEGER}
    select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        delete from shop
        where ID = #{id,jdbcType=INTEGER}
    delete>
    <insert id="insert" parameterType="com.myProject.model.Shop">
        insert into shop (ID, shopAddr, shopIcon,
        shopName, shopStatus, userId)
        values (#{id,jdbcType=INTEGER}, #{shopAddr,jdbcType=VARCHAR},
        #{shopIcon,jdbcType=VARCHAR},
        #{shopName,jdbcType=VARCHAR}, #{shopStatus,jdbcType=INTEGER}, #{userId,jdbcType=INTEGER})
    insert>
    
    <insert id="insertSelective" parameterType="com.myProject.model.Shop"
        useGeneratedKeys="true" keyProperty="id">
        insert into shop
        
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                ID,
            if>
            <if test="shopAddr != null">
                shopAddr,
            if>
            <if test="shopIcon != null">
                shopIcon,
            if>
            <if test="shopName != null">
                shopName,
            if>
            <if test="shopStatus != null">
                shopStatus,
            if>
            <if test="userId != null">
                userId,
            if>
        trim> 
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            if>
            <if test="shopAddr != null">
                #{shopAddr,jdbcType=VARCHAR},
            if>
            <if test="shopName != null">
                #{shopName,jdbcType=VARCHAR},
            if>
            <if test="shopIcon != null">
                #{shopIcon,jdbcType=VARCHAR},
            if>
            <if test="shopStatus != null">
                #{shopStatus,jdbcType=INTEGER},
            if>
            <if test="userId != null">
                #{userId,jdbcType=INTEGER},
            if>
        trim>
    insert>
    <update id="updateByPrimarykey" parameterType="com.myProject.model.Shop">
        update shop
        set shopAddr = #{shopAddr,jdbcType=VARCHAR},
        shopIcon = #{shopIcon,jdbcType=VARCHAR},
        shopName = #{shopName,jdbcType=VARCHAR},
        shopStatus = #{shopStatus,jdbcType=INTEGER},
        where ID = #{id,jdbcType=INTEGER}
    update>
    <select id="getShopList" parameterType="com.myProject.model.Shop"
        resultMap="BaseResultMap">
        select
        s.ID, s.shopAddr, s.shopIcon, s.shopName, s.shopStatus
        from shop s
        
        where 1=1
        <if test="shopAddr!=null and shopAddr!=''">
            and s.shopAddr like '%${shopAddr}%'
        if>
        <if test="shopName != null and shopAddr!=''">
            and s.shopName = #{shopName,jdbcType=VARCHAR}
        if>
        <if test="shopStatus != null and shopStatus != 0">
            and s.shopStatus = #{shopStatus,jdbcType=INTEGER}
        if>
        order by s.ID asc
        <if test="pageIndex!=null">
            limit #{pageIndex},#{pageSize}
        if>
    select>
mapper>

これで1つのエンティティクラスに関するDAOメソッドを構成することができて、Javaコードで直接DAOを書くよりも難しいと感じて、誰が私にデータベースをよく勉強させませんか?
@Autowiredオートインジェクション
たとえば、商品リストコントローラがある場合、商品Commと店舗Shopを操作する必要がある場合は、このコントローラクラスに2つのエンティティクラスのサービスを追加する必要があります.私の以前の方法では、new ClassPathXmlApplicationContext("beans.xml").getBean(name)でサービスのbeanを取得することができます.ここでは注釈Autowiredを使って自動的に注入され、newなどは必要ありませんので、この商品リストコントローラはこのように書くことができます.
package com.myProject.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myProject.model.Comm;
import com.myProject.model.Shop;
import com.myProject.service.CommService;
import com.myProject.service.ShopService;

@Controller
@RequestMapping(value="/comm")
public class CommController {

    @Autowired
    private CommService commService;

    @Autowired
    private ShopService shopSerivce;

    /**
     *            
     * @param request
     * @return
     */
    @RequestMapping(value="/system/getCommList.do")
    /**           ,           new  People,         new Person(),     People people               ,      people,   new **/
    public @ResponseBody Map getCommList(HttpServletRequest request) {
        String strIndex = request.getParameter("pageIndex");
        String strSize = request.getParameter("pageSize");
        Integer shopId = Integer.parseInt(request.getParameter("shopId"));
        Shop shop = this.shopSerivce.selectByPrimaryKey(shopId);
        int pageIndex = 0;
        int pageSize = 10;
        if(strIndex.isEmpty() || strIndex.equals("")) {} else {
            try {
                pageIndex = Integer.parseInt(strIndex);
            } catch(ClassCastException e) {

            }
        }
        if(strSize.isEmpty() || strSize.equals("")) {} else {
            try {
                pageSize = Integer.parseInt(strSize);
            } catch(ClassCastException e) {

            }
        }

        Comm comm = new Comm();
        comm.setShopId(shopId);
        comm.setPageIndex(pageIndex);
        comm.setPageSize(pageSize);
        List comms = this.commService.getCommList(comm);
        Map map = new HashMap();
        map.put("shop", shop);
        map.put("commlist", comms);
        return map;
    }
    
    @RequestMapping(value="/system/initComm.do")
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public @ResponseBody Map init() throws Exception {
        Map map = new HashMap();
        for(int i = 0; i < 20; i++) {
            Comm comm = new Comm();
            comm.setCommIcon("images/mobile/page/shaxianxiaochi.jpg");
            comm.setCommName("  "+i);
            comm.setCommPrice(new BigDecimal(Math.random()*10.0));
            comm.setCommStatus(1);
            comm.setShopId(1);
            this.commService.insert(comm);
        }
        return null;
    }
}

完全なエンティティと関連機能
まずShopという実体クラスが必要です.例えばShopです.このShop実体クラスにはShopAddr、ShopNameなどの属性のほかにpageSizeとpageIndexを書いて指定範囲内のShopリストを検索し、xmlでこの実体クラスに関するDAOメソッドを構成した後、ShopMapper店舗マッピングインタフェースを作成し、ShopServiceのメソッドを定義します.その後、同じShopServiceインタフェースをもう一つ書きます.何のために使われているのか分かりませんが、ShopServiceImplクラスを作成してShopServiceインタフェースを実現します.この実装クラスではShopMapper属性を明記し、その後、この接続方法を実現します.方法の内容はthis.shopMapper.methodNameだけです.次は完全な例です
エンティティークラス
package com.myProject.model;

/**
 *     
 * @author Slience
 *
 */
public class Shop {

    private Integer id;

    private String shopAddr;

    private String shopIcon;

    private String shopName;

    private Integer shopStatus;

    private Integer userId;

    private Integer pageSize;

    private Integer pageIndex;


    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getPageIndex() {
        return pageIndex;
    }

    public void setPageIndex(Integer pageIndex) {
        this.pageIndex = pageIndex;
    }

    public Integer getId() {
        return id;
    }

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


    public String getShopAddr() {
        return shopAddr;
    }

    public void setShopAddr(String shopAddr) {
        this.shopAddr = shopAddr;
    }


    public String getShopIcon() {
        return shopIcon;
    }

    public void setShopIcon(String shopIcon) {
        this.shopIcon = shopIcon;
    }

    public String getShopName() {
        return shopName;
    }

    public void setShopName(String shopName) {
        this.shopName = shopName;
    }


    public Integer getShopStatus() {
        return shopStatus;
    }

    public void setShopStatus(Integer shopStatus) {
        this.shopStatus = shopStatus;
    }

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }


}

mybatisプロファイル


<mapper namespace="com.myProject.dao.ShopMapper">
    <resultMap id="BaseResultMap" type="com.myProject.model.Shop">
        <id column="ID" property="id" jdbcType="INTEGER" />
        <result column="shopAddr" property="shopAddr" jdbcType="VARCHAR" />
        <result column="shopIcon" property="shopIcon" jdbcType="VARCHAR" />
        <result column="shopName" property="shopName" jdbcType="VARCHAR" />
        <result column="shopStatus" property="shopStatus" jdbcType="INTEGER" />
        <result column="userId" property="userId" jdbcType="INTEGER" />
    resultMap>
    <sql id="Base_Column_List">
        ID, shopAddr, shopIcon, shopName, shopStatus, userId
    sql>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap"
        parameterType="java.lang.Integer">
        select
        <include refid="Base_Column_List" />
        from shop
        where ID = #{id,jdbcType=INTEGER}
    select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
        delete from shop
        where ID = #{id,jdbcType=INTEGER}
    delete>
    <insert id="insert" parameterType="com.myProject.model.Shop">
        insert into shop (ID, shopAddr, shopIcon,
        shopName, shopStatus, userId)
        values (#{id,jdbcType=INTEGER}, #{shopAddr,jdbcType=VARCHAR},
        #{shopIcon,jdbcType=VARCHAR},
        #{shopName,jdbcType=VARCHAR}, #{shopStatus,jdbcType=INTEGER}, #{userId,jdbcType=INTEGER})
    insert>
    <insert id="insertSelective" parameterType="com.myProject.model.Shop"
        useGeneratedKeys="true" keyProperty="id">
        insert into shop
        
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="id != null">
                ID,
            if>
            <if test="shopAddr != null">
                shopAddr,
            if>
            <if test="shopIcon != null">
                shopIcon,
            if>
            <if test="shopName != null">
                shopName,
            if>
            <if test="shopStatus != null">
                shopStatus,
            if>
            <if test="userId != null">
                userId,
            if>
        trim> 
        <trim prefix="values (" suffix=")" suffixOverrides=",">
            <if test="id != null">
                #{id,jdbcType=INTEGER},
            if>
            <if test="shopAddr != null">
                #{shopAddr,jdbcType=VARCHAR},
            if>
            <if test="shopName != null">
                #{shopName,jdbcType=VARCHAR},
            if>
            <if test="shopIcon != null">
                #{shopIcon,jdbcType=VARCHAR},
            if>
            <if test="shopStatus != null">
                #{shopStatus,jdbcType=INTEGER},
            if>
            <if test="userId != null">
                #{userId,jdbcType=INTEGER},
            if>
        trim>
    insert>
    <update id="updateByPrimarykey" parameterType="com.myProject.model.Shop">
        update shop
        set shopAddr = #{shopAddr,jdbcType=VARCHAR},
        shopIcon = #{shopIcon,jdbcType=VARCHAR},
        shopName = #{shopName,jdbcType=VARCHAR},
        shopStatus = #{shopStatus,jdbcType=INTEGER},
        where ID = #{id,jdbcType=INTEGER}
    update>
    <select id="getShopList" parameterType="com.myProject.model.Shop"
        resultMap="BaseResultMap">
        select
        s.ID, s.shopAddr, s.shopIcon, s.shopName, s.shopStatus
        from shop s
        where 1=1
        <if test="shopAddr!=null and shopAddr!=''">
            and s.shopAddr like '%${shopAddr}%'
        if>
        <if test="shopName != null and shopAddr!=''">
            and s.shopName = #{shopName,jdbcType=VARCHAR}
        if>
        <if test="shopStatus != null and shopStatus != 0">
            and s.shopStatus = #{shopStatus,jdbcType=INTEGER}
        if>
        order by s.ID asc
        <if test="pageIndex!=null">
            limit #{pageIndex},#{pageSize}
        if>
    select>
mapper>

Mapperインタフェース
package com.myProject.dao;

import java.util.List;

import com.myProject.model.Shop;

public interface ShopMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(Shop shop);

    int insertSelective(Shop shop);

    Shop selectByPrimaryKey(Integer id);

    int updateByPrimarykey(Shop shop);

    //        
    public List getShopList(Shop shop);

}

Serviceインタフェース(Mapperそっくり)
package com.dreamlife.service;

import java.util.List;

import com.dreamlife.model.Shop;

public interface ShopService {
    int deleteByPrimaryKey(Integer id);

    int insert(Shop shop);

    int insertSelective(Shop shop);

    Shop selectByPrimaryKey(Integer id);

    int updateByPrimarykey(Shop shop);

    //        
    public List getShopList(Shop shop);
}

インタフェース実装クラスServiceImpl
package com.dreamlife.serviceImpl;

import java.util.List;

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

import com.dreamlife.dao.ShopMapper;
import com.dreamlife.model.Shop;
import com.dreamlife.service.ShopService;

public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        // TODO Auto-generated method stub
        return this.shopMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(Shop shop) {
        // TODO Auto-generated method stub
        return this.shopMapper.insert(shop);
    }
    @Override
    public Shop selectByPrimaryKey(Integer id) {
        // TODO Auto-generated method stub
        return this.shopMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimarykey(Shop shop) {
        // TODO Auto-generated method stub
        return this.shopMapper.updateByPrimarykey(shop);
    }
    @Override
    public List getShopList(Shop shop) {
        // TODO Auto-generated method stub
        return this.shopMapper.getShopList(shop);
    }

    @Override
    public int insertSelective(Shop shop) {
        // TODO Auto-generated method stub
        return this.shopMapper.insertSelective(shop);
    }
}

Controllerクラス
package com.myProject.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.myProject.model.Shop;
import com.myProject.service.ShopService;

@Controller
@RequestMapping(value="/shop")
public class ShopController {

    @Autowired
    private ShopService shopService;    //   service



    @RequestMapping(value="/system/getShopList.do")
    public @ResponseBody Map getShopList(HttpServletRequest request) {
        Shop shop = new Shop();
        shop.setPageSize(4);
        shop.setPageIndex(1);
        List shops = this.shopService.getShopList(shop);
        Mapmap = new HashMap();
        map.put("message", "Success");
        map.put("aaData", shops);
        return map;
    }
    @RequestMapping(value="/system/addShop.do")
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public @ResponseBody Map addShop(HttpServletRequest request,Shop shop) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String shopAddr = request.getParameter("shopAddr");
        String shopIcon = request.getParameter("shopIcon");
        String shopName = request.getParameter("shopName");
        Integer shopStatus = Integer.parseInt(request.getParameter("shopStatus"));
        Integer userId = Integer.parseInt(request.getParameter("userId"));
        shop.setShopAddr(shopAddr);
        shop.setShopIcon(shopIcon);
        shop.setShopName(shopName);
        shop.setShopStatus(shopStatus);
        shop.setUserId(userId);
        this.shopService.insertSelective(shop);
        //     
        return null;
    }

}