MyBatis的增刪改查。
阿新 • • 發佈:2017-11-18
etag close jdbc .org comm 我們 ack Coding ins
數據庫的經典操作:增刪改查。
在這一章我們主要說明一下簡單的查詢和增刪改,並且對程序接口做了一些調整,以及對一些問題進行了解答。
1、調整後的結構圖:
2、連接數據庫文件配置分離:
一般的程序都會把連接數據庫的配置單獨放在.properties 文件中,然後在XML文件中引用,示例如下:
config.properties:
driver=oracle.jdbc.OracleDriver url=jdbc:oracle:thin:@127.0.0.1:1521:orcl username=phonesurvey password=world
mybatis-config.xml:
![技術分享圖片](/img/fz.gif)
![技術分享圖片](https://common.cnblogs.com/images/copycode.gif)
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="config.properties" /> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${driver}"/> <property name="url" value="${url}"/> <property name="username" value="${username}"/> <property name="password" value="${password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="nankang/dao/agentDao.xml" /> </mappers> </configuration>
![技術分享圖片](https://common.cnblogs.com/images/copycode.gif)
![技術分享圖片](/img/fz.gif)
3、SqlSession分離:
SqlSeesion單獨做成工具類,以便調用,示例如下:
SqlSessionHelper:
![技術分享圖片](/img/fz.gif)
![技術分享圖片](https://common.cnblogs.com/images/copycode.gif)
package nankang.util; import java.io.InputStream; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class SqlSessionHelper { public static SqlSessionFactory getSessionFactory(){ SqlSessionFactory sessionFactory = null; String resource= "mybatis-config.xml"; try{ InputStream inputStream = Resources.getResourceAsStream(resource); //Reader reader = Resources.getResourceAsReader(resource); sessionFactory = new SqlSessionFactoryBuilder().build(inputStream); }catch(Exception ex){ ex.printStackTrace(); } return sessionFactory; } }
![技術分享圖片](https://common.cnblogs.com/images/copycode.gif)
![技術分享圖片](/img/fz.gif)
SqlSessionFactory創建時,根據Reader和InputStream都可以。
4、XML文件添加內容:
agentDao.xml:
![技術分享圖片](/img/fz.gif)
![技術分享圖片](https://common.cnblogs.com/images/copycode.gif)
<?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="nankang.dao.AgentDao"> <!-- 根據Id查詢 --> <select id="selectAgentById" parameterType="string" resultType="nankang.po.Agent"> select * from Agent where AgentId=#{id} </select> <!-- 添加 --> <insert id="insertAgent" parameterType="nankang.po.Agent"> insert into Agent(agentId, companyCode, LoginName, AgentPwd, AgentCode, Name, status,sysFlag) values(#{agentId},‘SHNK‘,#{loginName},‘D41D8CD98F00B204E9800998ECF8427E‘,#{agentCode},#{name},1,1) </insert> <!-- 刪除 --> <delete id="deleteAgent" parameterType="string"> delete from Agent where agentid=#{id} </delete> <!-- 修改 --> <update id="updateAgent" parameterType="nankang.po.Agent"> update agent set name=#{name} where agentid=#{agentId} </update> <!-- 查詢所有 --> <select id="selectAllAgent" resultType="nankang.po.Agent"> select * from Agent </select> <!-- 查詢所有無返回對象 --> <select id="selectAllAgent2" resultType="hashmap"> select * from Agent </select> </mapper>
![技術分享圖片](https://common.cnblogs.com/images/copycode.gif)
![技術分享圖片](/img/fz.gif)
AgentDao.java:
![技術分享圖片](/img/fz.gif)
![技術分享圖片](https://common.cnblogs.com/images/copycode.gif)
package nankang.dao; import java.util.List; import java.util.Map; import nankang.po.Agent; import org.apache.ibatis.annotations.Select; public interface AgentDao { //根據Id查詢 public Agent selectAgentById(String Id); //根據名稱查詢 @Select("select * from Agent where name=#{name}") public Agent selectAgentByName(String name); //添加 public int insertAgent(Agent agent); //刪除 public int deleteAgent(String id); //修改 public int updateAgent(Agent agent); //查詢所有的 public List<Agent> selectAllAgent(); public List<Map<String, Object>> selectAllAgent2(); }
![技術分享圖片](https://common.cnblogs.com/images/copycode.gif)
![技術分享圖片](/img/fz.gif)
1、XML文件中的語句,可以直接寫在接口文件中,如:根據名稱查詢;
2、其他參考示例。
幾個問題說明:
1)如何查詢數據集合?
使用ResultType設置,返回用List<T>即可
2)查詢一條數據,如果為空,怎麽判斷?
如果沒有查詢到數據,返回為NULL,進行空對象判斷即可
3)查詢所有的集合,不放在構建對象的List中:
resultType=map,返回類型 List<Map<String,Object>>,字段為空則不展示在Map中4)如何實現事務:
SqlSession:commit,rollback,close
5、測試
![技術分享圖片](/img/fz.gif)
![技術分享圖片](https://common.cnblogs.com/images/copycode.gif)
package nankang.test; import java.util.List; import java.util.Map; import nankang.dao.AgentDao; import nankang.util.SqlSessionHelper; import org.apache.ibatis.session.SqlSession; public class test { /** * @param args */ public static void main(String[] args) { SqlSession sqlSession = SqlSessionHelper.getSessionFactory().openSession(); try{ AgentDao agentMapper = sqlSession.getMapper(AgentDao.class); //根據Id查詢 // Agent agent = agentMapper.selectAgentById("SHNKAG00000000051"); // if(null != agent){ // System.out.println(agent.getName()); // }else{ // System.out.println("不存在該用戶"); // } // agent = agentMapper.selectAgentByName("1001"); // System.out.println(agent.getAgentId()); //查詢所有 List<Map<String, Object>> agentList = agentMapper.selectAllAgent2(); System.out.println(agentList.size()); //添加 // Format format = new SimpleDateFormat("00yyyyMMddhhmmss"); // Calendar calendar = Calendar.getInstance(); // String dateStr = format.format(calendar.getTime()); // Agent agent = new Agent(); // agent.setAgentId(dateStr); // agent.setLoginName("1111"); // agent.setAgentCode("aaaa"); // agent.setName("aaaa"); // int num = agentMapper.insertAgent(agent); // System.out.println(num); //刪除 // int num = agentMapper.deleteAgent("0020150226093127"); // System.out.println(num); //更新 // Agent agent = new Agent(); // agent.setAgentId("0020150226010005"); // agent.setName("Test"); // int num = agentMapper.updateAgent(agent); // System.out.println(num); //增刪改,提交 sqlSession.commit(); System.out.println("完成"); }catch(Exception ex){ sqlSession.rollback(); System.out.println(ex.getMessage()); }finally{ sqlSession.close(); } } }
![技術分享圖片](https://common.cnblogs.com/images/copycode.gif)
![技術分享圖片](/img/fz.gif)
這邊需要註意的是:SqlSession一定要close
MyBatis的增刪改查。