解析Mybatis入门第三天
目的:使用mybatis对数据的一些标签的使用和表与表之间的一对多和多对一的查询方式。
例如:if、where、foreach
前言:同样是使用idea创建一个普通的maven工程(如何创建一个普通的Maven工程可以参考入门第一天的详解)。
数据库的使用和前两天的一样,除此之外,新添加两张表,方便后面对一对多和多对一的操作打基础。
同样先查看整个项目的结构:
开始进入代码编辑。。。
- 在前两次的使用的数据库的基础上创建两张表。
CREATE TABLE `account` ( `ID` int(11) NOT NULL COMMENT '编号', `UID` int(11) default NULL COMMENT '用户编号', `MONEY` double default NULL COMMENT '金额', PRIMARY KEY (`ID`), KEY `FK_Reference_8` (`UID`), CONSTRAINT `FK_Reference_8` FOREIGN KEY (`UID`) REFERENCES `user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `account`(`ID`,`UID`,`MONEY`) values (1,1,1000),(2,2,1000),(3,2,2000); ----------------------------------------分割--------------------------------------------------- CREATE TABLE `role` ( `ID` int(11) NOT NULL COMMENT '编号', `ROLE_NAME` varchar(30) default NULL COMMENT '角色名称', `ROLE_DESC` varchar(60) default NULL COMMENT '角色描述', PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `role`(`ID`,`ROLE_NAME`,`ROLE_DESC`) values (1,'组长','管理整个组'),(2,'班主任','管理整个班级'),(3,'校长','管理整个学校'); CREATE TABLE `user_role` ( `UID` int(11) NOT NULL COMMENT '用户编号', `RID` int(11) NOT NULL COMMENT '角色编号', PRIMARY KEY (`UID`,`RID`), KEY `FK_Reference_10` (`RID`), CONSTRAINT `FK_Reference_10` FOREIGN KEY (`RID`) REFERENCES `role` (`ID`), CONSTRAINT `FK_Reference_9` FOREIGN KEY (`UID`) REFERENCES `user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; insert into `user_role`(`UID`,`RID`) values (1,1),(1,2),(2,2);
- 在项目的pom.xml文件中引入本次需要的坐标
1 <dependencies> 2 <!-- mybatis坐标 --> 3 <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> 4 <dependency> 5 <groupId>org.mybatis</groupId> 6 <artifactId>mybatis</artifactId> 7 <version>3.4.5</version> 8 </dependency> 9 <!--mysql驱动包--> 10 <dependency> 11 <groupId>mysql</groupId> 12 <artifactId>mysql-connector-java</artifactId> 13 <version>5.1.6</version> 14 </dependency> 15 <!--单元测试--> 16 <dependency> 17 <groupId>junit</groupId> 18 <artifactId>junit</artifactId> 19 <version>4.10</version> 20 <scope>test</scope> 21 </dependency> 22 <!-- https://mvnrepository.com/artifact/log4j/log4j --> 23 <!--日志--> 24 <dependency> 25 <groupId>log4j</groupId> 26 <artifactId>log4j</artifactId> 27 <version>1.2.17</version> 28 </dependency> 29 </dependencies>
- 配置需要的文件,在resources的文件下添加一个日志属性文件:log4j.properties
# Set root category priority to INFO and its only appender to CONSOLE. #log4j.rootCategory=INFO, CONSOLE debug info warn error fatal log4j.rootCategory=debug, CONSOLE # Set the enterprise logger category to FATAL and its only appender to CONSOLE. log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE # CONSOLE is set to be a ConsoleAppender using a PatternLayout. log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n # LOGFILE is set to be a File appender using a PatternLayout. log4j.appender.LOGFILE=org.apache.log4j.FileAppender #log4j.appender.LOGFILE.File=d:\axis.log log4j.appender.LOGFILE.File=axis.log log4j.appender.LOGFILE.Append=true log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n
- 同样是在resources的目录下添加一个连接数据库的属性文件,配置数据库的连接:jdbc.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/javaDemo?characterEncoding=utf8 username=root password=root
- 最后在resources下配置最最最重要的文件:SqlMapConfig.xml。具体的讲解在文件中看注释
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 <configuration> 6 <!--加载jdbc的属性配置文件--> 7 <properties resource="jdbc.properties"/> 8 <!--配置实体类的别名--> 9 <typeAliases> 10 <!-- 11 type:实体类的全路径 12 alias:取的一个别名,不区分大小写,在配置文件调用这个实体类的时候就可以使用别名。 13 --> 14 <typeAlias type="zh.test.domain.NBAPlaers" alias="nbaers"/> 15 <typeAlias type="zh.test.domain.Account" alias="account"/> 16 <typeAlias type="zh.test.domain.Role" alias="role"/> 17 <!--同样上面的可以写为 : 如果有多个实体类可以写为:包名。别名则就是【类名】--> 18 <!--<package name="zh.test.domain"/>--> 19 </typeAliases> 20 <!--配置多个环境--> 21 <environments default="mysql"> 22 <!--配置环境--> 23 <environment id="mysql"> 24 <!-- 25 配置事物管理,使用本地的事物策略 26 使用mysql数据库,事务管理方式 27 1、手动提交事物/回滚事物 setAutoCommit(false),mybatis默认事物的管理方式 28 2、自动提交事物,设置自动提交的方式,不推荐使用。 29 --> 30 <transactionManager type="JDBC"></transactionManager> 31 <!--是否要是要连接池 POOLED:使用内置连接。 UNPOOLED:不使用连接池,底层创建连接池的方式。 使用JNDI连接池--> 32 <dataSource type="POOLED"> 33 <property name="driver" value="${driver}"/> 34 <property name="url" value="${url}"/> 35 <property name="username" value="${username}"/> 36 <property name="password" value="${password}"/> 37 <!--<property name="url" value="jdbc:mysql:///javaDemo"/>--> 38 </dataSource> 39 </environment> 40 </environments> 41 <!--引入映射的配置文件,在本配置文件加载的时候就会加载在这里你配置的文件--> 42 <mappers> 43 <mapper resource="mappers/Usermapper.xml"></mapper> 44 <mapper resource="mappers/Accountmapper.xml"></mapper> 45 <mapper resource="mappers/Rolemapper.xml"></mapper> 46 </mappers> 47 </configuration>
- 编写NBAPlaers、Role、Account的Java文件,注意在每个Java文件中都要实现
Serializable的接口。
Account.java:1 package zh.test.domain; 2 3 import java.io.Serializable; 4 5 public class Account implements Serializable { 6 private Integer id; 7 private Integer uid; 8 private Double money; 9 private NBAPlaers nbaPlaers; 10 11 @Override 12 public String toString() { 13 return "Account{" + 14 "id=" + id + 15 ", uid=" + uid + 16 ", money=" + money + 17 ", nbaPlaers=" + nbaPlaers + 18 '}'; 19 } 20 21 public NBAPlaers getNbaPlaers() { 22 return nbaPlaers; 23 } 24 25 public void setNbaPlaers(NBAPlaers nbaPlaers) { 26 this.nbaPlaers = nbaPlaers; 27 } 28 29 public Integer getId() { 30 return id; 31 } 32 33 public void setId(Integer id) { 34 this.id = id; 35 } 36 37 public Integer getUid() { 38 return uid; 39 } 40 41 public void setUid(Integer uid) { 42 this.uid = uid; 43 } 44 45 public Double getMoney() { 46 return money; 47 } 48 49 public void setMoney(Double money) { 50 this.money = money; 51 } 52 }
NBAplaers.java:
1 package zh.test.domain; 2 3 import java.io.Serializable; 4 import java.util.Date; 5 import java.util.List; 6 7 /* 8 编写一个User的实体类,并且实现Serializable接口,目的只是表示一个类的对象可以被序列化。 9 什么是Serializable接口? 10 一个对象序列化的接口,一个类只有实现了Serializable接口,他的对象才能被序列化 11 */ 12 public class NBAPlaers implements Serializable { 13 private Integer id; 14 private String username; 15 private Date birthday; 16 private String sex; 17 private String address; 18 private List<Integer> ids; 19 private List<Account> accounts; 20 21 public List<Account> getAccounts() { 22 return accounts; 23 } 24 25 public void setAccounts(List<Account> accounts) { 26 this.accounts = accounts; 27 } 28 29 public List<Integer> getIds() { 30 return ids; 31 } 32 33 public void setIds(List<Integer> ids) { 34 this.ids = ids; 35 } 36 37 @Override 38 public String toString() { 39 return "NBAPlaers{" + 40 "id=" + id + 41 ", username='" + username + '\'' + 42 ", birthday=" + birthday + 43 ", sex='" + sex + '\'' + 44 ", address='" + address + '\'' + 45 ", ids=" + ids + 46 ", accounts=" + accounts + 47 '}'; 48 } 49 50 public Integer getId() { 51 return id; 52 } 53 54 public void setId(Integer id) { 55 this.id = id; 56 } 57 58 public String getUsername() { 59 return username; 60 } 61 62 public void setUsername(String username) { 63 this.username = username; 64 } 65 66 public Date getBirthday() { 67 return birthday; 68 } 69 70 public void setBirthday(Date birthday) { 71 this.birthday = birthday; 72 } 73 74 public String getSex() { 75 return sex; 76 } 77 78 public void setSex(String sex) { 79 this.sex = sex; 80 } 81 82 public String getAddress() { 83 return address; 84 } 85 86 public void setAddress(String address) { 87 this.address = address; 88 } 89 }
Role.java:
1 package zh.test.domain; 2 3 import java.io.Serializable; 4 import java.util.List; 5 6 public class Role implements Serializable { 7 private Integer id; 8 private String role_name; 9 private String role_desc; 10 //一个角色可以对应多个人员 11 private List<NBAPlaers> nbaers; 12 13 public Integer getId() { 14 return id; 15 } 16 17 public void setId(Integer id) { 18 this.id = id; 19 } 20 21 public String getRole_name() { 22 return role_name; 23 } 24 25 public void setRole_name(String role_name) { 26 this.role_name = role_name; 27 } 28 29 public String getRole_desc() { 30 return role_desc; 31 } 32 33 public void setRole_desc(String role_desc) { 34 this.role_desc = role_desc; 35 } 36 37 public List<NBAPlaers> getNbaers() { 38 return nbaers; 39 } 40 41 public void setNbaers(List<NBAPlaers> nbaers) { 42 this.nbaers = nbaers; 43 } 44 45 @Override 46 public String toString() { 47 return "Role{" + 48 "id=" + id + 49 ", role_name='" + role_name + '\'' + 50 ", role_desc='" + role_desc + '\'' + 51 ", nbaers=" + nbaers + 52 '}'; 53 } 54 }
- 编写相对应的接口,在接口中写对应的方法
UserMapper:
1 package zh.test.mapper; 2 3 import zh.test.domain.NBAPlaers; 4 5 import java.util.List; 6 7 /* 8 用户映射接口 9 */ 10 public interface UserMapper { 11 //根据条件查询 12 public NBAPlaers findById(int id); 13 //多条件语句拼接查询 14 public List<NBAPlaers> findByIds(NBAPlaers nbaPlaers); 15 //使用foreach循环 16 public List<NBAPlaers> findByeach(NBAPlaers nbaPlaers); 17 //一对多的查询方式 18 public List<NBAPlaers> findMany(); 19 }
AccountMapper:
1 package zh.test.mapper; 2 3 import zh.test.domain.Account; 4 5 import java.util.List; 6 7 public interface AccountMapper { 8 // 多对一的两张表的数据查询 9 public List<Account> findAll(); 10 11 }
RoleMapper:
1 package zh.test.mapper; 2 3 import zh.test.domain.Role; 4 5 import java.util.List; 6 7 public interface RoleMapper { 8 public List<Role> findAll(); 9 }
- 在mappers的文件夹下面分别写一下几个文件。(三个文件会在SqlMapConfig.xml的文件引入一下的几个配置文件)
Usermapper.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!--约束 dtd约束--> 3 <!DOCTYPE mapper 4 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 5 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 6 <!-- 7 namespace:用来区分mapper接口的,一般写mapper的全路径 8 --> 9 10 <mapper namespace="zh.test.mapper.UserMapper"> 11 12 <!--根据条件查询--> 13 <!-- 14 id:findById 方法的名称 15 parameterType:方法参数的类型 16 resultType:方法返回值的类型 17 18 ? 不能使用?作为占位符,使用#{} 或${}来编写,推荐使用#{} 19 区别:1、#{}. 20 2、${} 21 以上两种,当方法的参数为【引用类型】的时候,两种都可以使用,没有区别 22 当方法的参数为【普通数据类型(int double )】推荐使用#{此处的方法的名字可以随意命名},但是${此处的方法的名字的参数必须与写value} 23 --> 24 <select id="findById" parameterType="java.lang.Integer" resultType="zh.test.domain.NBAPlaers"> 25 select * from NBAPlaers where id=#{id} 26 </select> 27 <!-- 28 拼接sql语句 29 根据条件判断是否要添加后面的条件 30 --> 31 <select id="findByIds" parameterType="nbaers" resultType="nbaers"> 32 select * from NBAPlaers 33 <where> 34 <if test="username !=null and username !=''"> 35 and username like #{username} 36 </if> 37 </where> 38 </select> 39 <!--抽取公共的部分--> 40 <select id="findWhere"> 41 select * from NBAPlaers 42 </select> 43 <!--使用foreach循环--> 44 <select id="findByeach" parameterType="nbaers" resultType="nbaers"> 45 select * from NBAPlaers 46 <where> 47 -- collection:要遍历的集合 48 -- open="开始" close="关闭的" separator="分割" item="遍历后的变量" index="下标值" 49 <foreach collection="ids" open="id = " separator="or id = " item="i"> 50 #{i} 51 </foreach> 52 </where> 53 </select> 54 <!--通过两张表之间的关联,查询一对多的查询方式 55 56 --> 57 <select id="findMany" resultMap="Unfind"> 58 SELECT n.*,n.id nid,a.id aid ,a.money FROM account a,NBAPlaers n where a.uid=n.id 59 </select> 60 <resultMap id="Unfind" type="nbaers"> 61 <result property="id" column="id"/> 62 <result property="username" column="username"/> 63 <result property="sex" column="sex"/> 64 <collection property="accounts" ofType="Account"> 65 <result property="id" column="aid"/> 66 <result property="money" column="money"/> 67 </collection> 68 </resultMap> 69 </mapper>
Accountmapper.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!--约束 dtd约束--> 3 <!DOCTYPE mapper 4 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 5 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 6 <!-- 7 namespace:用来区分mapper接口的,一般写mapper的全路径 8 --> 9 10 <mapper namespace="zh.test.mapper.UserMapper"> 11 12 <!--根据条件查询--> 13 <!-- 14 id:findById 方法的名称 15 parameterType:方法参数的类型 16 resultType:方法返回值的类型 17 18 ? 不能使用?作为占位符,使用#{} 或${}来编写,推荐使用#{} 19 区别:1、#{}. 20 2、${} 21 以上两种,当方法的参数为【引用类型】的时候,两种都可以使用,没有区别 22 当方法的参数为【普通数据类型(int double )】推荐使用#{此处的方法的名字可以随意命名},但是${此处的方法的名字的参数必须与写value} 23 --> 24 <select id="findById" parameterType="java.lang.Integer" resultType="zh.test.domain.NBAPlaers"> 25 select * from NBAPlaers where id=#{id} 26 </select> 27 <!-- 28 拼接sql语句 29 根据条件判断是否要添加后面的条件 30 --> 31 <select id="findByIds" parameterType="nbaers" resultType="nbaers"> 32 select * from NBAPlaers 33 <where> 34 <if test="username !=null and username !=''"> 35 and username like #{username} 36 </if> 37 </where> 38 </select> 39 <!--抽取公共的部分--> 40 <select id="findWhere"> 41 select * from NBAPlaers 42 </select> 43 <!--使用foreach循环--> 44 <select id="findByeach" parameterType="nbaers" resultType="nbaers"> 45 select * from NBAPlaers 46 <where> 47 -- collection:要遍历的集合 48 -- open="开始" close="关闭的" separator="分割" item="遍历后的变量" index="下标值" 49 <foreach collection="ids" open="id = " separator="or id = " item="i"> 50 #{i} 51 </foreach> 52 </where> 53 </select> 54 <!--通过两张表之间的关联,查询一对多的查询方式 55 56 --> 57 <select id="findMany" resultMap="Unfind"> 58 SELECT n.*,n.id nid,a.id aid ,a.money FROM account a,NBAPlaers n where a.uid=n.id 59 </select> 60 <resultMap id="Unfind" type="nbaers"> 61 <result property="id" column="id"/> 62 <result property="username" column="username"/> 63 <result property="sex" column="sex"/> 64 <collection property="accounts" ofType="Account"> 65 <result property="id" column="aid"/> 66 <result property="money" column="money"/> 67 </collection> 68 </resultMap> 69 </mapper>
Rolemapper.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <!--约束 dtd约束--> 3 <!DOCTYPE mapper 4 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 5 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 6 <!-- 7 namespace:用来区分mapper接口的,一般写mapper的全路径 8 --> 9 <!-- 10 多对多的查询,拆分为一对多 11 --> 12 <mapper namespace="zh.test.mapper.RoleMapper"> 13 <select id="findAll" resultMap="roleMapper"> 14 SELECT r.*,n.username FROM NBAPlaers n,role r,nba_role nr WHERE nr.uid=n.id and r.id=nr.rid; 15 </select> 16 <resultMap id="roleMapper" type="role"> 17 <result property="id" column="id"/> 18 <result property="role_name" column="role_name"/> 19 <result property="role_desc" column="role_desc"/> 20 <collection property="nbaers" ofType="nbaers"> 21 <result property="username" column="username"/> 22 </collection> 23 </resultMap> 24 </mapper>
- 最后对不同的模块不同的功能做测试,其中在最前面的项目结构截图test下面的Demo、Demo2、Demo3分别对应模块UserMapper、AccountMapper、RoleMapper
Demo:
1 package test; 2 3 import org.apache.ibatis.io.Resources; 4 import org.apache.ibatis.session.SqlSession; 5 import org.apache.ibatis.session.SqlSessionFactory; 6 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 7 import org.junit.Test; 8 import zh.test.domain.NBAPlaers; 9 import zh.test.mapper.UserMapper; 10 11 import java.io.IOException; 12 import java.io.InputStream; 13 import java.util.ArrayList; 14 import java.util.List; 15 16 public class Demo { 17 //根据id查询数据 18 @Test 19 public void findById() throws IOException { 20 InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml"); 21 SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream); 22 SqlSession sqlSession = build.openSession(); 23 UserMapper mapper = sqlSession.getMapper(UserMapper.class); 24 NBAPlaers nbaPlaer = mapper.findById(2); 25 System.out.println(nbaPlaer); 26 sqlSession.close(); 27 resourceAsStream.close(); 28 // 这里代码看不懂可以查看mybatis01的代码 29 } 30 31 // 根据多条件的方式查询,在UserMapper.xml 文件中使用where和if的标签拼接查询方式 32 @Test 33 public void findByIds() throws IOException { 34 InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml"); 35 SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream); 36 SqlSession sqlSession = build.openSession(); 37 UserMapper mapper = sqlSession.getMapper(UserMapper.class); 38 NBAPlaers nbaPlaers=new NBAPlaers(); 39 nbaPlaers.setUsername("%o%"); 40 List<NBAPlaers> byIds = mapper.findByIds(nbaPlaers); 41 for(NBAPlaers n:byIds) 42 { 43 System.out.println(n); 44 } 45 sqlSession.close(); 46 resourceAsStream.close(); 47 } 48 // 使用foreach循环,在UserMapper.xml 文件中使用foreach的标签循环 49 @Test 50 public void findByforeachIds() throws IOException { 51 InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml"); 52 SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream); 53 SqlSession sqlSession = build.openSession(); 54 UserMapper mapper = sqlSession.getMapper(UserMapper.class); 55 NBAPlaers nbaPlaers=new NBAPlaers(); 56 List<Integer> list=new ArrayList<Integer>(); 57 list.add(1); 58 list.add(2); 59 list.add(3); 60 nbaPlaers.setIds(list); 61 List<NBAPlaers> byIds = mapper.findByeach(nbaPlaers); 62 for(NBAPlaers n:byIds) 63 { 64 System.out.println(n); 65 } 66 sqlSession.close(); 67 resourceAsStream.close(); 68 } 69 // 一对多通过两张表之间的关联查询数据 70 @Test 71 public void findTwoTable() throws IOException { 72 InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml"); 73 SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream); 74 SqlSession sqlSession = build.openSession(); 75 UserMapper mapper = sqlSession.getMapper(UserMapper.class); 76 List<NBAPlaers> byIds = mapper.findMany(); 77 for(NBAPlaers n:byIds) 78 { 79 System.out.println(n); 80 } 81 sqlSession.close(); 82 resourceAsStream.close(); 83 } 84 }
Demo2:
1 package test; 2 3 import org.apache.ibatis.io.Resources; 4 import org.apache.ibatis.session.SqlSession; 5 import org.apache.ibatis.session.SqlSessionFactory; 6 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 7 import org.junit.Test; 8 import zh.test.domain.Account; 9 import zh.test.domain.NBAPlaers; 10 import zh.test.mapper.AccountMapper; 11 import zh.test.mapper.UserMapper; 12 13 import java.io.IOException; 14 import java.io.InputStream; 15 import java.util.ArrayList; 16 import java.util.List; 17 18 public class Demo2 { 19 20 // 多对一的查询方式 21 @Test 22 public void findByAll() throws IOException { 23 InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml"); 24 SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream); 25 SqlSession sqlSession = build.openSession(); 26 AccountMapper mapper = sqlSession.getMapper(AccountMapper.class); 27 List<Account> all = mapper.findAll(); 28 for (Account account : all) { 29 System.out.println(account); 30 } 31 sqlSession.close(); 32 resourceAsStream.close(); 33 } 34 }
Demo3:
1 package test; 2 3 import org.apache.ibatis.io.Resources; 4 import org.apache.ibatis.session.SqlSession; 5 import org.apache.ibatis.session.SqlSessionFactory; 6 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 7 import org.junit.Test; 8 import zh.test.domain.Role; 9 import zh.test.mapper.RoleMapper; 10 11 import java.io.IOException; 12 import java.io.InputStream; 13 import java.util.List; 14 15 public class Demo3 { 16 // 17 @Test 18 public void findAll() throws IOException { 19 InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml"); 20 SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsStream); 21 SqlSession sqlSession = build.openSession(); 22 RoleMapper mapper = sqlSession.getMapper(RoleMapper.class); 23 List<zh.test.domain.Role> all = mapper.findAll(); 24 for (Role role : all) { 25 System.out.println(role); 26 } 27 sqlSession.close(); 28 resourceAsStream.close(); 29 } 30 }
分享之路,欢迎交流。。。