标签:style blog http ar io color os 使用 sp
MyBatis
mybatis和hibernate都属于orm(对象与关系映射) 框架
mybatis的优点:
1.sql-mapping :操作更自由,可控性高,执行效率更高
2.轻量,学习更容易
3.维护和修改容易
mybatis使用场合:
在不需要太多复杂的功能,且需要性能更高,并且希望更灵活可以使用mybatis
什么时候不宜使用mybatis:
对象持久化对程序完全透明时,使用hibernate
当数据有移植需求且需要支持多种数据库是
当应用程序要求完全动态sql时
没有使用关系数据库时
使用mybatis需要使用到架包:
下载架包
下面开始我么第一个mybatis练习:、
1.建一个项目:
2.配置mybatis-config.xml (帮助文档 里面可以查找到 )
3.建一个实体类
4.创建一个mapper文件 (可以在帮助文档里面查看)
5.创建dao 封装类
6.测试
先上代码:
mybatis-config.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 <settings> 7 <setting name="cacheEnabled" value="true"/> 8 9 </settings> 10 <!-- --> 11 <environments default="development"> 12 <environment id="development"> 13 <!-- 事务处理方式 --> 14 <transactionManager type="JDBC"/> 15 <!-- 数据源 :提供数据库连接池 --> 16 <dataSource type="POOLED"> 17 <!-- 驱动 --> 18 <property name="driver" value="oracle.jdbc.driver.OracleDriver"/> 19 <!-- --> 20 <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"/> 21 <property name="username" value="super_user"/> 22 <property name="password" value="abc123"/> 23 </dataSource> 24 </environment> 25 </environments> 26 27 28 <!-- 映射文件,可以配置多个 --> 29 <mappers> 30 <mapper resource="dao/grade.xml"/> 31 32 </mappers> 33 34 35 </configuration>
grade.xml:
1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <mapper namespace="dao.MyBatis01Dao"> 6 <cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true"/> 7 <!-- parameterType="int" 指定传入参数类型 id最好与接口里面的方法名一致--> 8 <select id="testgetGrade" resultType="entity.Grade"> 9 select * from grade where gradeid=1 10 </select> 11 <resultMap type="entity.Grade" id="gradeMap"> 12 13 </resultMap> 14 <select id="testBatis1" parameterType="int" resultMap="gradeMap"> 15 select * from grade where gradeid>=#{gradeid} 16 </select> 17 <select id="seleTrend" parameterType="entity.Grade" resultType="entity.Grade"> 18 select * from grade where 1=1 19 <if test ="gradeid != null"> 20 <![CDATA[ 21 and gradeid<= #{gradeid} 22 ]]> 23 24 </if> 25 <if test ="gradename != null"> 26 <!-- 模糊查询 --> 27 <![CDATA[ 28 and gradename like ‘%${gradename}%‘ 29 ]]> 30 </if> 31 32 33 </select> 34 35 <insert id="insertGrade" parameterType="entity.Grade" flushCache="true" > 36 insert into grade values(#{gradeid},#{gradename}) 37 38 </insert> 39 <insert id="insertGradeBySeq" parameterType="entity.Grade" flushCache="true"> 40 <selectKey keyProperty="gradeid" resultType="int" order="BEFORE"> 41 select seq_gradeindex.nextVal from dual 42 </selectKey> 43 insert into grade values(#{gradeid},#{gradename}) 44 45 </insert> 46 <delete id="delGrade" parameterType="entity.Grade" flushCache="true" > 47 delete grade where gradeid=#{gradeid} 48 49 </delete> 50 <update id="upGrade" parameterType="entity.Grade" flushCache="true" > 51 update grade set gradename=#{gradename} where gradeid=#{gradeid} 52 53 </update> 54 55 56 57 <!-- 动态查询 --> 58 <select id="testTrendSele1" parameterType="entity.Student" resultType="entity.Student"> 59 select * from student where 1=1 60 <if test="stuno != null"> 61 <![CDATA[ 62 and stuno<=#{stuno} 63 ]]> 64 65 </if> 66 <if test="name != null"> 67 <![CDATA[ 68 and name like ‘%${name}%‘ 69 ]]> 70 </if> 71 <if test="gradeid != null"> 72 <![CDATA[ 73 and gradeid>=#{gradeid} 74 ]]> 75 </if> 76 77 </select> 78 <!-- MyBatis where 查询 --> 79 <select id="testTrendSeleByWhere" parameterType="entity.Student" resultType="entity.Student"> 80 select * from student 81 <where> 82 <if test="stuno != null"> 83 <![CDATA[ 84 and stuno<=#{stuno} 85 ]]> 86 87 </if> 88 <if test="name != null"> 89 <![CDATA[ 90 and name like ‘%${name}%‘ 91 ]]> 92 </if> 93 <if test="gradeid != null"> 94 <![CDATA[ 95 and gradeid>=#{gradeid} 96 ]]> 97 </if> 98 </where> 99 100 </select> 101 <!-- choose查询 --> 102 <select id="testTrendSeleByChoose" parameterType="entity.Student" resultType="entity.Student"> 103 104 select * from student where 1=1 105 <choose> 106 <when test="stuno != null"> 107 <![CDATA[ 108 and stuno<=#{stuno} 109 ]]> 110 </when> 111 <when test="name != null"> 112 <![CDATA[ 113 and name like ‘%${name}%‘ 114 ]]> 115 </when> 116 <otherwise> 117 <![CDATA[ 118 and gradeid>=#{gradeid} 119 ]]> 120 </otherwise> 121 </choose> 122 123 </select> 124 <!-- set 动态更新 --> 125 <update id="testTrendSeleBySet" parameterType="entity.Grade"> 126 update grade 127 <set> 128 <if test="gradename != null"> 129 gradename=#{gradename} 130 </if> 131 132 </set> 133 where gradeid=#{gradeid} 134 135 </update> 136 137 </mapper>
dao.GradeDaoImpl:
1 package dao.impl; 2 3 import java.io.Reader; 4 import java.util.List; 5 6 import junit.framework.TestCase; 7 import org.apache.ibatis.io.Resources; 8 import org.apache.ibatis.session.SqlSession; 9 import org.apache.ibatis.session.SqlSessionFactory; 10 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 11 import org.junit.Test; 12 13 import util.MyBatisUtil; 14 15 import dao.MyBatis01Dao; 16 import entity.Grade; 17 import entity.Student; 18 19 public class GradeImplDao extends TestCase implements MyBatis01Dao{ 20 21 22 String resource="mybatis-config.xml"; 23 Reader reader=null; 24 SqlSessionFactory factory=null; 25 SqlSession session=null; 26 /** 27 * 测试 有参方法 28 */ 29 30 public void testV(){ 31 try { 32 //session=(new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource))).openSession(); 33 //MyBatis01Dao con=session.getMapper(MyBatis01Dao.class); 34 //con.testBatis1(5); 35 36 //testBatis1(2); 37 // Grade grade=new Grade(); 38 // grade.setGradeid(7); 39 // grade.setGradename(""); 40 //delGrade(grade); 41 //insertGrade(grade); 42 //upGrade(grade); 43 //seleTrend(grade); 44 Student student=new Student(25,"ab%d",2); 45 //testTrendSele1(student); 46 testTrendSeleByChoose(student); 47 //testTrendSeleByWhere(student); 48 //testTrendSeleBySet(student); 49 } catch (Exception e) { 50 // TODO: handle exception 51 e.printStackTrace(); 52 } 53 finally{ 54 //session.close(); 55 } 56 57 } 58 /** 59 * 第一个mybatis查询 60 */ 61 62 public void testgetGrade(){ 63 try { 64 //读取配置文件 65 reader=Resources.getResourceAsReader(resource); 66 SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder(); 67 //创建sqlsessionfactory 68 factory=builder.build(reader); 69 session=factory.openSession(); 70 //读取 71 List grade=session.selectList("testgetGrade"); 72 System.out.println(grade); 73 } catch (Exception e) { 74 // TODO: handle exception 75 e.printStackTrace(); 76 }finally{ 77 session.close(); 78 79 } 80 81 82 } 83 84 /** 85 * 传入一个参数查询 seleGradeByPara 86 */ 87 public void testBatis1(int id){ 88 try { 89 //创建并且打开session 90 session=(new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource))).openSession(); 91 //设置参数 92 List grade=session.selectList("testBatis1",id); 93 System.out.println(grade); 94 } catch (Exception e) { 95 e.printStackTrace(); 96 }finally{ 97 //关闭 98 session.close(); 99 100 } 101 } 102 103 104 105 106 /** 107 * 新增 108 */ 109 @Override 110 public void insertGrade(Grade grade) { 111 try { 112 //打开 113 session=(new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource))).openSession(); 114 //新增 115 session.insert("insertGrade",grade); 116 session.commit(); 117 //显示 118 System.out.println(session.selectList("testBatis1",1)); 119 } catch (Exception e) { 120 // TODO: handle exception 121 e.printStackTrace(); 122 }finally{ 123 session.close(); 124 } 125 126 } 127 128 /** 129 * 删除指定 130 * @param grade 131 */ 132 public void delGrade(Grade grade){ 133 try { 134 session=(new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource))).openSession(); 135 session.delete("delGrade",grade); 136 session.commit(); 137 System.out.println(session.selectList("testBatis1",1)); 138 139 } catch (Exception e) { 140 // TODO: handle exception 141 e.printStackTrace(); 142 }finally{ 143 session.close(); 144 } 145 146 } 147 /** 148 * 更新 149 * @param grade 150 */ 151 public void upGrade(Grade grade){ 152 try { 153 session=(new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource))).openSession(); 154 session.update("upGrade",grade); 155 session.commit(); 156 System.out.println(session.selectList("testBatis1",1)); 157 } catch (Exception e) { 158 // TODO: handle exception 159 e.printStackTrace(); 160 }finally{ 161 session.close(); 162 } 163 } 164 165 /** 166 * 动态查询 167 * @param grade 168 */ 169 public void seleTrend(Grade grade){ 170 try { 171 session=(new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource))).openSession(); 172 173 System.out.println(session.selectList("seleTrend", grade)); 174 175 } catch (Exception e) { 176 // TODO: handle exception 177 e.printStackTrace(); 178 }finally{ 179 session.close(); 180 } 181 182 } 183 184 /** 185 * 测试更新 186 */ 187 public void testForUpdate(){ 188 try { 189 session=new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource)).openSession(); 190 Grade grade=new Grade(); 191 grade.setGradename("研究院"); 192 session.insert("insertGradeBySeq",grade); 193 session.commit(); 194 } catch (Exception e) { 195 // TODO: handle exception 196 e.printStackTrace(); 197 session.rollback(); 198 }finally{ 199 session.close(); 200 201 } 202 203 } 204 205 @Override 206 public void testTrendSele1(Student student) { 207 try { 208 //System.out.println("111111111"); 209 session=(new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource))).openSession(); 210 List students=session.selectList("testTrendSele1",student); 211 for(int i=0;i<students.size();i++){ 212 System.out.println(students.get(i)); 213 214 215 } 216 217 218 } catch (Exception e) { 219 e.printStackTrace(); 220 } 221 finally{ 222 if(session != null) 223 session.close(); 224 } 225 } 226 227 @Override 228 public void testTrendSeleByWhere(Student student) { 229 // TODO Auto-generated method stub 230 try { 231 session=new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource)).openSession(); 232 //代替 where 1=1 where字句 233 List students=session.selectList("testTrendSeleByWhere",student); 234 for(int i=0;i<students.size();i++){ 235 System.out.println(students.get(i)); 236 237 238 } 239 } catch (Exception e) { 240 e.printStackTrace(); 241 } 242 finally{ 243 session.close(); 244 } 245 } 246 247 @Override 248 public void testTrendSeleByChoose(Student student) { 249 // TODO Auto-generated method stub 250 try { 251 session=MyBatisUtil.getSession(); 252 //choose: 只查询 其中一个条件,从上到下执行 253 List students=session.selectList("testTrendSeleByChoose",student); 254 for(int i=0;i<students.size();i++){ 255 System.out.println(students.get(i)); 256 257 258 } 259 MyBatisUtil.closeSession(); 260 session=MyBatisUtil.getSession(); 261 List students2=session.selectList("testTrendSeleByChoose",student); 262 System.out.println("---------"+(students==students2)+"----------"); 263 264 } catch (Exception e) { 265 e.printStackTrace(); 266 } 267 finally{ 268 MyBatisUtil.closeSession(); 269 } 270 271 272 } 273 274 @Override 275 public void testTrendSeleBySet(Student student) { 276 // TODO Auto-generated method stub 277 try { 278 session=new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader(resource)).openSession(); 279 Grade grade=new Grade(); 280 grade.setGradeid(2); 281 grade.setGradename("一年级"); 282 session.update("testTrendSeleBySet", grade); 283 session.commit(); 284 System.out.println("success!"); 285 } catch (Exception e) { 286 e.printStackTrace(); 287 session.rollback(); 288 } 289 finally{ 290 MyBatisUtil.closeSession(); 291 } 292 293 294 } 295 296 297 @Test 298 public void testname() { 299 System.out.println("11111"); 300 } 301 302 303 304 }
entity.Grade
1 package entity; 2 3 import java.io.Serializable; 4 import java.util.HashSet; 5 import java.util.Set; 6 /** 7 * 年级实体类 8 * @author Administrator 9 * 10 */ 11 public class Grade implements Serializable{ 12 //年级编号 13 private Integer gradeid; 14 //年级 15 private String gradename; 16 17 @Override 18 public String toString() { 19 // TODO Auto-generated method stub 20 return gradeid+"\t"+gradename; 21 } 22 23 public Grade(){} 24 25 26 public Integer getGradeid() { 27 return gradeid; 28 } 29 public void setGradeid(Integer gradeid) { 30 this.gradeid = gradeid; 31 } 32 public String getGradename() { 33 return gradename; 34 } 35 public void setGradename(String gradename) { 36 this.gradename = gradename; 37 } 38 39 40 41 }
config配置文件中:
主要配置了数据库连接信息
以及映射文件的位置信息
mapper配置文件:
配置了各种sql语句,与config关联起来需要在config里面写上这句代码:
<mappers>
<mapper resource="dao/grade.xml"/>
</mappers>
mybatis支持哪些操作:
增 删 改 查
实现普通查询:
1.配置mapper
<mapper namespace="dao接口包"/>
<select id="testgetGrade" resultType="entity.Grade">
select * from grade where gradeid=1
</select>
解释:
id:我们在dao.impl里面去操作数据库时,指定sql语句就根据id指定,id尽量与接口提供的方法同名(后面讲getMapper()可以看出作用 )
resultType:返回值类型,支持各种类型
2.在dao里面写代码:
mybatis也是基于session的
1、声明一个sqlSessionFactory对象、SqlSession对象、Reader对象
2、读取配置文件
//指定config路径
String resource="mybatis-config.xml";
//读取配置文件
reader=Resources.getResourceAsReader(resource);
//声明sqlsessionfactorybuilder
SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
//创建sqlsessionfactory
factory=builder.build(reader);
//开启sqlsession
session=factory.openSession();
//读取
List grade=session.selectList("testgetGrade");
//打印
System.out.println(grade);
暂时介绍select方法;
selectlist方法返回的是一个list集合
上面的代码里面包含了,查询,删除,修改,新增,动态查询,缓存的方法,结合帮助文档可以看明白
下次做详细深入的总结
标签:style blog http ar io color os 使用 sp
原文地址:http://www.cnblogs.com/gcs1995/p/4169039.html