【接口式编程】尚未遇见Spring --> 代码量反而增加
1、增加约定,减少犯错的可能(不用直接去写字符串
修改点1:命名空间
修改点2:增加接口,方法名与配置文件中的id对应
package com.imooc.dao; import java.util.List; import com.imooc.bean.Message; /** * * 与配置文件Message相对应的接口 * */ public interface IMessage { // 代言SQL语句 public List<Message> queryMessageList(Message message); public void deleteOne(int id); public void deleteBatch(List<Integer> ids); }
修改点3:修改DAO层调用SQL的方式
package com.imooc.dao; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.imooc.bean.Message; import com.imooc.db.DBAccess; /** * 和message表相关的数据库操作 */ public class MessageDAO { public List<Message> queryMessageList(String command, String description) { DBAccess dbAccess = new DBAccess(); SqlSession sqlSession = null; List<Message> messageList = null; try { sqlSession = dbAccess.getSqlSession(); Message message = new Message(); message.setCommand(command); message.setDescription(description); // 通过sqlSession执行SQL语句 IMessage iMessage = sqlSession.getMapper(IMessage.class); messageList = iMessage.queryMessageList(message); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } return messageList; } /** * 单条删除 */ public void deletOne(int id) { DBAccess dbAccess = new DBAccess(); SqlSession sqlSession = null; try { sqlSession = dbAccess.getSqlSession(); // 通过sqlSession执行SQL语句 IMessage iMessage = sqlSession.getMapper(IMessage.class); iMessage.deleteOne(id); sqlSession.commit(); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } } /** * 删除多条消息 */ public void deleteBatch(List<Integer> ids) { DBAccess dbAccess = new DBAccess(); SqlSession sqlSession = null; try { sqlSession = dbAccess.getSqlSession(); // 通过sqlSession执行SQL语句 IMessage iMessage = sqlSession.getMapper(IMessage.class); iMessage.deleteBatch(ids); sqlSession.commit(); } catch (IOException e) { e.printStackTrace(); } finally { if (sqlSession != null) { sqlSession.close(); } } } }
【只写接口,不写实现】
1、添加依赖包
2、编写 XxxDAO 接口 (结果集 + 行为 + 参数)
3、用 XxxDAO.xml 实现接口( SQL)