SqlMapConfig.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> <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:///test"/> <property name = "username" value = "root"/> <property name = "password" value = "1234"/> </dataSource> </environment> </environments> <mappers> <mapper resource = "com/entity/Dept.xml"/> </mappers> </configuration>
Dept:
package com.entity; /** * Created by samdi on 2016/3/3. */ public class Dept { private Integer deptno; private String dname; private String loc; public String getLoc() { return loc; } public void setLoc(String loc) { this.loc = loc; } public String getDname() { return dname; } public void setDname(String dname) { this.dname = dname; } public Integer getDeptno() { return deptno; } public void setDeptno(Integer deptno) { this.deptno = deptno; } }
Dept.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="com.entity.DeptMapper"> <insert id = "addDept" parameterType="com.entity.Dept"> insert into T_DEPT (DEPTNO,DNAME,LOC) values (#{deptno},#{dname},#{loc}) </insert> <select id = "findAll" resultType = "com.entity.Dept"> select DEPTNO,DNAME,LOC from T_DEPT </select> </mapper>
DeptMapper:
package com.entity; import java.util.List; /** * Created by samdi on 2016/3/3. */ public interface DeptMapper { public void addDept(Dept dept); public List<Dept> findAll(); }
test类,以其中一个为例:
package com.test; import com.entity.Dept; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.RowBounds; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import org.junit.Test; import java.io.IOException; import java.io.Reader; import java.util.List; /** * Created by 无名 on 2016/3/3. */ public class TestPage { @Test public void testFindPage() throws IOException{ String conf = "SqlMapConfig.xml"; Reader reader = Resources.getResourceAsReader(conf); //创建session对象 SqlSessionFactoryBuilder ssfb = new SqlSessionFactoryBuilder(); SqlSessionFactory ssf = ssfb.build(reader); //创建session SqlSession session= ssf.openSession(); //起点,从0开始 int offset = 0; //查几条 int limit = 3; RowBounds rowBounds = new RowBounds(offset,limit); List<Dept> list = session.selectList("findAll",null,rowBounds); for(Dept dept:list){ System.out.println(dept.getDeptno() + " " + dept.getDname() + " " + dept.getLoc()); } session.close(); } }
运行: