本文共 3513 字,大约阅读时间需要 11 分钟。
org.mybatis mybatis 3.3.0 org.mybatis mybatis-spring 1.2.3
jdbc.driverClassName=oracle.jdbc.driver.OracleDriverjdbc.url=jdbc:oracle:thin:@192.168.4.9:1521:orcl#jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatisjdbc.username=testjdbc.password=123456
创建SqlSessionFactory,需指定数据源,property名称必须为dataSource
创建数据映射器Mapper,属性mapperInterface的value必须为接口类
例 12.1. MyBatis
建立映射
package cn.netkiller.mapper;import org.apache.ibatis.annotations.Select;import org.apache.ibatis.annotations.Param;import cn.netkiller.model.User;public interface UserMapper { @Select("SELECT * FROM `user` WHERE id = #{id}") public User findById(@Param("id") int id); }
建立模型
package cn.netkiller.model;public class User { private String id; private String name; private int age; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", age=" + age + "]"; }}
建立 service
package cn.netkiller.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import cn.netkiller.mapper.UserMapper;import cn.netkiller.model.User;@Servicepublic class UserService { @Autowired private UserMapper userMapper; public UserMapper getUserMapper() { return userMapper; } public void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } public User findById(int id) { return userMapper.findById(id); }}
建立控制器
package cn.netkiller.controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.ModelMap;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.context.support.WebApplicationContextUtils;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.view.RedirectView;import cn.netkiller.mapper.UserMapper;import cn.netkiller.model.User;import cn.netkiller.service.UserService;@Controllerpublic class Index { @Autowired private UserMapper userMapper; @Autowired private UserService userService; @RequestMapping("/index") // @ResponseBody public ModelAndView index() { String message = "Hello"; return new ModelAndView("index/index", "variable", message); } @RequestMapping("/user") public ModelAndView user() { User user = userService.findById(2); String message = user.toString(); return new ModelAndView("index/index", "variable", message); } @RequestMapping("/member") public ModelAndView member() { User user = userMapper.findById(2); String message = user.toString(); return new ModelAndView("index/index", "variable", message); }}