(二)创建Model类
package com.model; public class OwnerNumInfo { private int id; public String phoneNum; public String ownerName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPhoneNum() { return phoneNum; } public void setPhoneNum(String phoneNum) { this.phoneNum = phoneNum; } public String getOwnerName() { return ownerName; } public void setOwnerName(String ownerName) { this.ownerName = ownerName; } public String toString() { return "User[id=" + id + " , ownerName=" + ownerName + " , phoneNum=" + phoneNum + "]"; } }
(三)创建DAO接口
package com.dao; import com.model.OwnerNumInfo; public interface OwnerNumInfoDao { public OwnerNumInfo getOwnerNumInfoDao(OwnerNumInfo owner); public boolean addOwnerNumInfo(OwnerNumInfo owner); public boolean deleteOwnerNumInfo(int id); public boolean updateOwnerNumInfo(OwnerNumInfo owner); }
(四)创建SQL语句映射文件
com.dao包下创建OwnerNumInfoDao.xml文件:
INSERT INTO ownernuminfo (id,ownerName,phoneNum) VALUES (#{id},#{ownerName},#{phoneNum}) UPDATE ownernuminfo SET ownerName=#{ownerName},phoneNum=#{phoneNum} WHERE id=#{id} DELETE FROM ownernuminfo WHERE id=#{id}
(四)编写MyBatis配置文件
src目录下创建mybatis-config.xml文件:
(五)编写Spring配置文件
src目录下创建ApplicationContext.xml文件:
org.gjt.mm.mysql.Driver jdbc:mysql://localhost:3306/phonenumdb?useUnicode=true&characterEncoding=UTF-8 root 1234
(六)编写测试类
src下创建test.java:
import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.dao.OwnerNumInfoDao; import com.model.OwnerNumInfo; public class test { /** * @param args */ public static void main(String[] args) { ApplicationContext ctx=null; ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); OwnerNumInfoDao ownerNumInfoDao=(OwnerNumInfoDao) ctx.getBean("ownerNumInfoDao"); OwnerNumInfo user=new OwnerNumInfo(); //添加两条数据 user.setId(1); user.setOwnerName("Jessica"); user.setPhoneNum("123"); ownerNumInfoDao.addOwnerNumInfo(user); user.setId(2); user.setOwnerName("Jessica2"); user.setPhoneNum("123"); ownerNumInfoDao.addOwnerNumInfo(user); System.out.println("添加成功"); //查询数据 user.setOwnerName("Jessica"); user.setPhoneNum("123"); System.out.println(ownerNumInfoDao.getOwnerNumInfoDao(user).toString()); user.setOwnerName("Jessica2"); user.setPhoneNum("123"); System.out.println(ownerNumInfoDao.getOwnerNumInfoDao(user).toString()); //修改数据 user.setId(2); user.setPhoneNum("802"); ownerNumInfoDao.updateOwnerNumInfo(user); System.out.println("修改成功"); //删除数据 ownerNumInfoDao.deleteOwnerNumInfo(1); System.out.println("删除成功"); } }
(七)用到的Jar包
除了Spring3.2和Mybatis3之外,还需要用到mybatis-spring-1.2.1.jar