目录
数据库的经典操作:增删改查。
在这一章我们主要说明一下简单的查询和增删改,并且对程序接口做了一些调整,以及对一些问题进行了解答。
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:
<?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>
3、SqlSession分离:
SqlSeesion单独做成工具类,以便调用,示例如下:
SqlSessionHelper:
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; } }
SqlSessionFactory创建时,根据Reader和InputStream都可以。
4、XML文件添加内容:
agentDao.xml:
<?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>
AgentDao.java:
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(); }
1、XML文件中的语句,可以直接写在接口文件中,如:根据名称查询;
2、其他参考示例。
几个问题说明:
1)如何查询数据集合?
使用ResultType设置,返回用List<T>即可
2)查询一条数据,如果为空,怎么判断?
如果没有查询到数据,返回为NULL,进行空对象判断即可
3)查询所有的集合,不放在构建对象的List中:
resultType=map,返回类型 List<Map<String,Object>>,字段为空则不展示在Map中
4)如何实现事务:
SqlSession:commit,rollback,close
5、测试
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(); } } }
这边需要注意的是:SqlSession一定要close