1. 程式人生 > >【框架】ssm的簡單例項-下篇

【框架】ssm的簡單例項-下篇

先看下專案結構圖:

先編寫控制器DictController和IndexController

@Controller
public class IndexController {
    @RequestMapping(value = {"", "/index"})
    public ModelAndView dicts() {
        ModelAndView mv = new ModelAndView("index");
        mv.addObject("now", new Date());
        return mv;
    }
}
@Controller
@RequestMapping("/dicts")
public class DictController {

    @Autowired
    private DictService dictService;

    /**
     * 顯示字典資料列表
     * 
     * @param sysDict
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping
    public ModelAndView dicts(SysDict sysDict, Integer offset, Integer limit) {
        ModelAndView mv = new ModelAndView("dicts");
        List<SysDict> dicts = dictService.findBySysDict(sysDict, offset, limit);
        mv.addObject("dicts", dicts);
        int count = dictService.getCount();
        mv.addObject("count", count);
        return mv;
    }

    /**
     * 新增或修改字典資訊頁面,使用 get 跳轉到頁面
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add(Long id) {
        ModelAndView mv = new ModelAndView("dict_add");
        SysDict sysDict;
        if(id == null){
        	//如果 id 不存在,就是新增資料,建立一個空物件即可
            sysDict = new SysDict();
        } else {
        	//如果 id 存在,就是修改資料,把原有的資料查詢出來
            sysDict = dictService.findById(id);
        }
        mv.addObject("model", sysDict);
        return mv;
    }

    /**
     * 新增或修改字典資訊,通過表單 post 提交資料
     * 
     * @param sysDict
     * @return
     */
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public ModelAndView save(SysDict sysDict) {
        ModelAndView mv = new ModelAndView();
        try {
            dictService.saveOrUpdate(sysDict);
            mv.setViewName("redirect:/dicts");
        } catch (Exception e){
            mv.setViewName("dict_add");
            mv.addObject("msg", e.getMessage());
            mv.addObject("model", sysDict);
        }
        return mv;
    }

    /**
     * 通過 id 刪除字典資訊
     * 
     * @param id
     * @return
     */
    @RequestMapping(value = "delete", method = RequestMethod.POST)
    @ResponseBody
    public ModelMap delete(@RequestParam Long id) {
        ModelMap modelMap = new ModelMap();
        try {
            boolean success = dictService.deleteById(id);
            modelMap.put("success", success);
        } catch (Exception e) {
            modelMap.put("success", false);
            modelMap.put("msg", e.getMessage());
        }
        return modelMap;
    }
    
    @RequestMapping(value = "count", method = RequestMethod.GET)
    public ModelMap getCount() {
    	ModelMap modelMap = new ModelMap();
    	 try {
             int count = dictService.getCount();
             modelMap.put("count", count);
         } catch (Exception e) {
             modelMap.put("success", false);
             modelMap.put("msg", e.getMessage());
         }
         return modelMap;
    }

}

下面編寫service層

public interface DictService {

    SysDict findById(Long id);

    List<SysDict> findBySysDict(SysDict sysDict, Integer offset, Integer limit);

    boolean saveOrUpdate(SysDict sysDict);

    boolean deleteById(Long id);
    
    int getCount();
}
@Service
public class DictServiceImpl implements DictService {

    @Autowired
    private DictMapper dictMapper;

    @Override
    public SysDict findById(Long id2) {
        return dictMapper.selectByPrimaryKey(id2);
    }

    public List<SysDict> findBySysDict(SysDict sysDict, Integer offset, Integer limit) {
        RowBounds rowBounds = RowBounds.DEFAULT;
        if(offset != null && limit != null){
            rowBounds = new RowBounds(offset, limit);
        }
        return dictMapper.selectBySysDict(sysDict, rowBounds);
    }

    @Override
    public boolean saveOrUpdate(SysDict sysDict) {
        if(sysDict.getId() == null){
            return dictMapper.insert(sysDict) == 1;
        } else {
            return dictMapper.updateById(sysDict) == 1;
        }
    }

    @Override
    public boolean deleteById(Long id) {
    	if(id == null){
    		throw new NullPointerException("id");
    	}
        return dictMapper.deleteById(id) == 1;
    }

	@Override
	public int getCount() {
		return dictMapper.getCount();
	}
}

下面編寫Model層

public class Memo {
	private Long id;
	private String info;
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getInfo() {
		return info;
	}
	public void setInfo(String info) {
		this.info = info;
	}

}
public class SysDict implements Serializable {
	private static final long serialVersionUID = 1L;
	private Long id;
    private String code;
    private String name;
    private String value;
    private List<Memo> memos;

    public Long getId() {
        return id;
    }

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

	public List<Memo> getMemos() {
		return memos;
	}

	public void setMemos(List<Memo> memos) {
		this.memos = memos;
	}
}

下面配置MyBatis介面和對映檔案

public interface DictMapper {

    /**
     * 根據主鍵查詢
     *
     * @param id
     * @return
     */
    SysDict selectByPrimaryKey(Long id);

    /**
     * 條件查詢
     *
     * @param sysDict
     * @return
     */
    List<SysDict> selectBySysDict(SysDict sysDict, RowBounds rowBounds);

    /**
     * 新增
     *
     * @param sysDict
     * @return
     */
    int insert(SysDict sysDict);

    /**
     * 根據主鍵更新
     *
     * @param sysDict
     * @return
     */
    int updateById(SysDict sysDict);

    /**
     * 根據主鍵刪除
     *
     * @param id
     * @return
     */
    int deleteById(Long id);
    
    int getCount();
}
<?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="tk.mybatis.web.mapper.DictMapper">
	 <resultMap id="SysDictMap" type="SysDict">
    	<id property="id" column="id"/>
    	<result property="code" column="code"/>
    	<result property="name" column="name"/>
    	<result property="value" column="value"/>
    	<collection property="memos" resultMap="memo">
    	</collection>
    </resultMap>
	<resultMap id="memo"  type="Memo">
    	<id property="id" column="mid"/>
    	<result property="info" column="info"/>
    </resultMap>
    
    <select id="getCount" resultType="Integer">
    select count(*) from sys_dict;
    </select>

    <select id="selectByPrimaryKey" resultMap="SysDictMap">
      select sys_dict.id, sys_dict.code, sys_dict.name, sys_dict.`value`,
      memo.id mid,
      memo.info info 
      from sys_dict  inner join memo  on sys_dict.id=memo.dictid   where sys_dict.id=#{id}
    </select>
   

	<select id="selectBySysDict" resultMap="SysDictMap">
		select * from sys_dict
		<where>
			<if test="id != null">
				and id = #{id}
			</if>
			<if test="code != null and code != ''">
				and code = #{code}
			</if>
		</where>
		order by code, `value`
	</select>
	<!--useGeneratedKeys屬性使用jdbc的getGeneratedKeys()獲取主鍵 ,並賦值給keyProperty屬性指定的屬性名  -->
    <insert id="insert" useGeneratedKeys="true" keyProperty="id">
		insert into sys_dict(code, name, value)
		values (#{code}, #{name}, #{value})
	</insert>

	<update id="updateById">
		update sys_dict
		set code = #{code},
			name = #{name},
			value = #{value}
		where id = #{id}
	</update>

	<delete id="deleteById">
		delete from sys_dict where id = #{id}
	</delete>

</mapper>

mybaits引數傳遞 #{abc}:MyBatis SQL中使用預編譯引數的一種方式,abc是傳入的引數名; (1)只有一個引數:此時mybatis並不關心引數叫什麼名字,就會直接把這個唯一的引數值拿來使用。 (2)多個引數 : 1.可以使用#{0},#{1}或者#{param1},#{param1},這種不直觀,且引數順序必須保證不變 2.可以把多個引數封裝成Map型別,key作為引數名 3.或者使用@param註解mybatis會自動把多個引數封裝成Map型別,省去手動構造Map引數過程。