先看下项目结构图:
先编写控制器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参数过程。