参考答案
在使用MyBatis框架时,主要涉及以下几个API:
1.SqlSessionFactoryBuilder该对象负责根据MyBatis配置文件SqlMapConfig.xml构建SqlSessionFactory实例。
2.SqlSessionFactory每一个MyBatis的应用程序都以一个SqlSessionFactory对象为核心。该对象负责创建SqlSession对象实例。
3.SqlSession该对象包含了所有执行SQL操作的方法,用于执行已映射的SQL语句。
参考答案
步骤一:在MySQL的test数据库中创建表和数据
请在MySQL的test数据库中新建表t_emp并插入测试数据,SQL语句如下所示:
create table t_emp( empno int auto_increment primary key, ename varchar(20), job varchar(10), mgr int, hiredate date, sal double, comm double, deptno int ); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (1,'SMITH','CLERK',3,'1980-5-12',800,null,20); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (2,'ALLEN','SALESMAN',3,'1981-6-3',1600,300,30); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (3,'WARD','SALESMAN',4,'1990-3-15',1250,500,30); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (4,'JONES','MANAGER',5,'1985-4-8',2975,null,20); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (5,'MARTIN','SALESMAN',7,'1986-3-8',1250,1400,30); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (6,'BLAKE','MANAGER',9,'1989-6-1',2850,null,30); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7,'CLARK','MANAGER',9,'1995-10-1',2450,null,10); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (8,'SCOTT','ANALYST',9,'1993-5-1',3000,null,20); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (9,'KING','PRESIDENT',null,'1988-8-8',5000,null,10); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (10,'TURNER','SALESMAN',5,'1983-2-1',1500,0,30); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (11,'ADAMS','CLERK',5,'1992-7-3',1100,null,20); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (12,'JAMES','CLERK',1,'1996-9-10',950,null,30); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (13,'FORD','ANALYST',1,'1993-1-1',3000,null,20); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (14,'MILLER','CLERK',3,'1983-10-9',1300,null,10);
步骤二:新建工程,导入jar包
新建名为SpringMyBatis_07_exec的Java工程,在该工程导入如图-1所示的jar包。
图-1
步骤三:新建SqlMapConfig.xml文件
新建SqlMapConfig.xml文件在工程的位置如图-2所示。
图-2
SqlMapConfig.xml文件中的代码如下所示:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd"> <configuration> <environments default="environment"> <environment id="environment"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> </configuration>
步骤四:新建Emp实体类
新建类Emp,该类在工程中的位置如图-3所示。
图- 3
Emp类文件中的代码如下所示:
package org.tarena.entity; import java.sql.Date; publicclass Emp { private Integer empno; private String ename; private String job; private Integer mgr; private Date hiredate; private Double sal; private Double comm; private Integer deptno; public Integer getEmpno() { return empno; } publicvoid setEmpno(Integer empno) { this.empno = empno; } public String getEname() { return ename; } publicvoid setEname(String ename) { this.ename = ename; } public String getJob() { return job; } publicvoid setJob(String job) { this.job = job; } public Integer getMgr() { return mgr; } publicvoid setMgr(Integer mgr) { this.mgr = mgr; } public Date getHiredate() { return hiredate; } publicvoid setHiredate(Date hiredate) { this.hiredate = hiredate; } public Double getSal() { return sal; } publicvoid setSal(Double sal) { this.sal = sal; } public Double getComm() { return comm; } publicvoid setComm(Double comm) { this.comm = comm; } public Integer getDeptno() { return deptno; } publicvoid setDeptno(Integer deptno) { this.deptno = deptno; } }
步骤五:新建EmpMapper接口和Emp.xml
新建EmpMapper接口和Emp.xml映射文件,这两个文件在工程中位置如下图-4所示:
图- 4
EmpMapper接口中的代码如下所示:
package org.tarena.entity; import java.util.List; import org.tarena.entity.Emp; public interface EmpMapper { public List<Emp> findAll(); public Emp findById(int id); public void addEmp(Emp emp); public void updateEmp(Emp emp); public void deleteById(int id); }
Emp.xml文件的代码如下所示:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <mapper namespace="org.tarena.entity.EmpMapper"> <insert id="addEmp" parameterType="org.tarena.entity.Emp"> insert into T_EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (#{empno},#{ename},#{job},#{mgr},#{hiredate}, #{sal},#{comm},#{deptno}) </insert> </mapper>
步骤六:修改SqlMapConfig.xml文件
修改SqlMapConfig.xml文件,加入图-5方块中的配置:
图- 5
步骤七:新建TestInsert类
新建类TestInsert,在该类中加入测试代码,代码如下所示:
package org.tarena.test; import java.io.IOException; import java.io.Reader; import java.sql.Date; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import org.tarena.entity.Emp; public class TestInsert { @Test public void testInsert() throws IOException{ String conf = "SqlMapConfig.xml"; Reader reader = Resources.getResourceAsReader(conf); //创建SessionFactory对象 SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder(); SqlSessionFactory sf = sfb.build(reader); //创建Session SqlSession session = sf.openSession(); //调用addEmp操作 Emp emp = new Emp(); emp.setEmpno(15); emp.setEname("jim"); emp.setJob("sales"); emp.setMgr(2); emp.setHiredate(new Date(System.currentTimeMillis())); emp.setSal(1000.00); emp.setComm(200.00); emp.setDeptno(30); session.insert("addEmp",emp); session.commit(); //关闭 session.close(); } }
步骤八:运行
在测试方法testInsert,运行成功后,查看数据库t_emp表,看数据是否插入成功。
步骤九:修改EmpMapper接口和Emp.xml
EmpMapper接口加入如图-6所示的代码。
图- 6
Emp.xml映射文件加入如图- 7所示的配置:
图- 7
步骤十:新建TestUpdate类
新建类TestUpdate,该类的代码如下所示:
package org.tarena.test; import java.io.IOException; import java.io.Reader; import java.sql.Date; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import org.tarena.entity.Emp; public class TestUpdate { @Test public void testUpdate() throws IOException{ String conf = "SqlMapConfig.xml"; Reader reader = Resources.getResourceAsReader(conf); //创建SessionFactory对象 SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder(); SqlSessionFactory sf = sfb.build(reader); //创建Session SqlSession session = sf.openSession(); //调用findById操作 Emp emp =(Emp)session.selectOne("findById",15); emp.setEname("tom"); emp.setJob("sales"); emp.setMgr(2); emp.setHiredate(new Date(System.currentTimeMillis())); emp.setSal(1000.00); emp.setComm(200.00); emp.setDeptno(30); //调用updateDept操作 session.update("updateEmp",emp); session.commit(); //关闭 session.close(); } }
步骤十一:运行TestUpdate测试
运行TestUpdate类的testUpdate测试方法,然后查看数据库t_emp表中的数据是否更新
步骤十二:修改EmpMapper接口和Emp.xml
EmpMapper接口加入如图-8所示的方法:
图- 8
Emp.xml映射文件加入如图-9所示的配置:
图- 9
步骤十三:新建TestDelete类
新建类TestDelete,该类的代码如下所示:
package org.tarena.test; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; public class TestDelete { @Test public void testDelete() throws IOException{ String conf = "SqlMapConfig.xml"; Reader reader = Resources.getResourceAsReader(conf); //创建SessionFactory对象 SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder(); SqlSessionFactory sf = sfb.build(reader); //创建Session SqlSession session = sf.openSession(); //调用deleteById操作 session.delete("deleteById",15); session.commit(); //关闭 session.close(); } }
步骤十四:运行TestDelete测试
运行TestDelete类的测试方法testDelete,然后查看数据库t_emp表中empno为15的数据是否被删除。
步骤十五:修改EmpMapper接口和Emp.xml
EmpMapper接口加入如图-10所示的代码:
图- 10
Emp.xml映射文件加入如图-11所示的配置:
图- 11
步骤十六:新建TestFind类
新建类TestFind,该类的代码如下所示:
package org.tarena.test; import java.io.IOException; import java.io.Reader; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import org.tarena.entity.Emp; public class TestFind { @Test public void testFindById() throws IOException{ String conf = "SqlMapConfig.xml"; Reader reader = Resources.getResourceAsReader(conf); //创建SessionFactory对象 SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder(); SqlSessionFactory sf = sfb.build(reader); //创建Session SqlSession session = sf.openSession(); //调用findById方法 Emp e = (Emp) session.selectOne("findById",1); System.out.println(e.getEmpno() +" "+e.getEname()+" "+e.getJob()+" "+e.getMgr() +" "+e.getHiredate()+" "+e.getSal()+" "+e.getComm()+" "+e.getDeptno()); //关闭 session.close(); } }
步骤十七:运行TestFind测试
运行TestFind类的测试方法testFindById,控制台输出如图-11所示的信息,说明测试成功。
图- 11
步骤十八:修改EmpMapper接口和Emp.xml
EmpMapper接口加入如图-12所示的代码:
图- 12
Emp.xml映射文件加入如图-13所示的配置:
图- 13
步骤十九:修改TestFind类
修改类TestFind,添加如图-14所示的测试方法:
图- 14
步骤二十:运行TestFind测试
运行TestFind类的测试方法testFindAll,控制台输出如图-15所示。
图- 15
Emp类的完整代码如下所示:
package org.tarena.entity; import java.sql.Date; publicclass Emp { private Integer empno; private String ename; private String job; private Integer mgr; private Date hiredate; private Double sal; private Double comm; private Integer deptno; public Integer getEmpno() { return empno; } publicvoid setEmpno(Integer empno) { this.empno = empno; } public String getEname() { return ename; } publicvoid setEname(String ename) { this.ename = ename; } public String getJob() { return job; } publicvoid setJob(String job) { this.job = job; } public Integer getMgr() { return mgr; } publicvoid setMgr(Integer mgr) { this.mgr = mgr; } public Date getHiredate() { return hiredate; } publicvoid setHiredate(Date hiredate) { this.hiredate = hiredate; } public Double getSal() { return sal; } publicvoid setSal(Double sal) { this.sal = sal; } public Double getComm() { return comm; } publicvoid setComm(Double comm) { this.comm = comm; } public Integer getDeptno() { return deptno; } publicvoid setDeptno(Integer deptno) { this.deptno = deptno; } }
EmpMapper接口的完整代码如下所示
package org.tarena.entity; import java.util.List; import org.tarena.entity.Emp; public interface EmpMapper { public void addEmp(Emp emp); public void updateEmp(Emp emp); public void deleteById(int id); public Emp findById(int id); public List<Emp> findAll(); }
Emp.xml映射文件的完整代码如下所示:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd"> <mapper namespace="org.tarena.entity.EmpMapper"> <select id="findAll" resultType="org.tarena.entity.Emp"> select EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO from T_EMP </select> <select id="findById" parameterType="int" resultType="org.tarena.entity.Emp"> select EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO from T_EMP where EMPNO=#{id} </select> <insert id="addEmp" parameterType="org.tarena.entity.Emp"> insert into T_EMP (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (#{empno},#{ename},#{job},#{mgr},#{hiredate}, #{sal},#{comm},#{deptno}) </insert> <delete id="deleteById" parameterType="int"> delete from T_EMP where EMPNO=#{no} </delete> <update id="updateEmp" parameterType="org.tarena.entity.Emp"> update T_EMP set ENAME=#{ename},JOB=#{job},MGR=#{mgr},HIREDATE=#{hiredate}, SAL=#{sal},COMM=#{comm},DEPTNO=#{deptno} where EMPNO=#{empno} </update> </mapper>
配置文件SqlMapConfig.xml的完整代码所示:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//ibatis.apache.org//DTD Config 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-config.dtd"> <configuration> <environments default="environment"> <environment id="environment"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/test" /> <property name="username" value="root" /> <property name="password" value="root" /> </dataSource> </environment> </environments> <mappers> <mapper resource="org/tarena/entity/Emp.xml" /> </mappers> </configuration>
测试类TestInsert的完整代码如下所示:
package org.tarena.test; import java.io.IOException; import java.io.Reader; import java.sql.Date; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import org.tarena.entity.Emp; public class TestInsert { @Test public void testInsert() throws IOException{ String conf = "SqlMapConfig.xml"; Reader reader = Resources.getResourceAsReader(conf); //创建SessionFactory对象 SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder(); SqlSessionFactory sf = sfb.build(reader); //创建Session SqlSession session = sf.openSession(); //调用addEmp操作 Emp emp = new Emp(); emp.setEmpno(15); emp.setEname("jim"); emp.setJob("sales"); emp.setMgr(2); emp.setHiredate(new Date(System.currentTimeMillis())); emp.setSal(1000.00); emp.setComm(200.00); emp.setDeptno(30); session.insert("addEmp",emp); session.commit(); //关闭 session.close(); } }
测试类TestUpdate的完整代码如下所示:
package org.tarena.test; import java.io.IOException; import java.io.Reader; import java.sql.Date; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import org.tarena.entity.Emp; public class TestUpdate { @Test public void testUpdate() throws IOException{ String conf = "SqlMapConfig.xml"; Reader reader = Resources.getResourceAsReader(conf); //创建SessionFactory对象 SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder(); SqlSessionFactory sf = sfb.build(reader); //创建Session SqlSession session = sf.openSession(); //调用findById操作 Emp emp =(Emp)session.selectOne("findById",15); emp.setEname("tom"); emp.setJob("sales"); emp.setMgr(2); emp.setHiredate(new Date(System.currentTimeMillis())); emp.setSal(1000.00); emp.setComm(200.00); emp.setDeptno(30); //调用updateDept操作 session.update("updateEmp",emp); session.commit(); //关闭 session.close(); } }
测试类TestDelete的完整代码如下所示:
package org.tarena.test; import java.io.IOException; import java.io.Reader; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; public class TestDelete { @Test public void testDelete() throws IOException{ String conf = "SqlMapConfig.xml"; Reader reader = Resources.getResourceAsReader(conf); //创建SessionFactory对象 SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder(); SqlSessionFactory sf = sfb.build(reader); //创建Session SqlSession session = sf.openSession(); //调用deleteById操作 session.delete("deleteById",15); session.commit(); //关闭 session.close(); } }
测试类TestFind的完整代码如下所示:
package org.tarena.test; import java.io.IOException; import java.io.Reader; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import org.tarena.entity.Emp; public class TestFind { @Test public void testFindById() throws IOException{ String conf = "SqlMapConfig.xml"; Reader reader = Resources.getResourceAsReader(conf); //创建SessionFactory对象 SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder(); SqlSessionFactory sf = sfb.build(reader); //创建Session SqlSession session = sf.openSession(); //调用findById方法 Emp e = (Emp) session.selectOne("findById",1); System.out.println(e.getEmpno() +" "+e.getEname()+" "+e.getJob()+" "+e.getMgr() +" "+e.getHiredate()+" "+e.getSal()+" "+e.getComm()+" "+e.getDeptno()); //关闭 session.close(); } @Test public void testFindAll() throws IOException{ String conf = "SqlMapConfig.xml"; Reader reader = Resources.getResourceAsReader(conf); //创建SessionFactory对象 SqlSessionFactoryBuilder sfb = new SqlSessionFactoryBuilder(); SqlSessionFactory sf = sfb.build(reader); //创建Session SqlSession session = sf.openSession(); //调用findAll方法 List<Emp> list = session.selectList("findAll"); for(Emp e : list){ System.out.println(e.getEmpno() +" "+e.getEname()+" "+e.getJob()+" "+e.getMgr() +" "+e.getHiredate()+" "+e.getSal()+" "+e.getComm()+" "+e.getDeptno()); } session.close(); } }
t_emp表及测试数据的完整SQL语句如下所示:
create table t_emp( empno int auto_increment primary key, ename varchar(20), job varchar(10), mgr int, hiredate date, sal double, comm double, deptno int ); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (1,'SMITH','CLERK',3,'1980-5-12',800,null,20); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (2,'ALLEN','SALESMAN',3,'1981-6-3',1600,300,30); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (3,'WARD','SALESMAN',4,'1990-3-15',1250,500,30); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (4,'JONES','MANAGER',5,'1985-4-8',2975,null,20); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (5,'MARTIN','SALESMAN',7,'1986-3-8',1250,1400,30); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (6,'BLAKE','MANAGER',9,'1989-6-1',2850,null,30); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (7,'CLARK','MANAGER',9,'1995-10-1',2450,null,10); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (8,'SCOTT','ANALYST',9,'1993-5-1',3000,null,20); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (9,'KING','PRESIDENT',null,'1988-8-8',5000,null,10); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (10,'TURNER','SALESMAN',5,'1983-2-1',1500,0,30); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (11,'ADAMS','CLERK',5,'1992-7-3',1100,null,20); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (12,'JAMES','CLERK',1,'1996-9-10',950,null,30); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (13,'FORD','ANALYST',1,'1993-1-1',3000,null,20); Insert into t_emp (EMPNO,ENAME,JOB,MGR,HIREDATE,SAL,COMM,DEPTNO) values (14,'MILLER','CLERK',3,'1983-10-9',1300,null,10);