20170314_mybatis学习笔记
iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO),同时还提供一个利用这个框架开发的 JPetStore实例。
鹿砦[lùzhài]
鹿砦:用伐倒树木构成、形似鹿角的筑城障碍物。古称鹿角砦。有树干鹿砦和树枝鹿砦两种。通常设置在森林边缘、林间道路和有行道树的道路上。
简单工程搭建
1、新建web工程
2、导入jar包
3、配置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 7 8 <!-- 配置mysql数据库的连接环境 --> 9 <environments default="q"> <!-- 环境 --> 10 <environment id="q"> 11 <transactionManager type="JDBC" /><!-- 事务管理器 --> 12 <dataSource type="POOLED"><!-- 数据源 --> 13 <property name="driver" value="com.mysql.jdbc.Driver" /> 14 <property name="url" value="jdbc:mysql://localhost:3306/cc3?useUnicode=true&characterEncoding=utf-8" /> 15 <property name="username" value="root" /> 16 <property name="password" value="root" /> 17 </dataSource> 18 </environment> 19 </environments> 20 21 22 <!-- 映射文件 --> 23 <mappers> 24 <mapper resource="com/hw/mapper/studentMapper.xml" /> 25 </mappers> 26 </configuration>
4、创建实体
1 package com.hw.entity; 2 3 import java.util.Date; 4 5 public class Student { 6 private int id; 7 private String name; 8 private float money; 9 private Date jobtime; 10 11 public Student(int id, String name, float money, Date jobtime) { 12 super(); 13 this.id = id; 14 this.name = name; 15 this.money = money; 16 this.jobtime = jobtime; 17 } 18 19 public Student(String name, float money, Date jobtime) { 20 super(); 21 this.name = name; 22 this.money = money; 23 this.jobtime = jobtime; 24 } 25 26 public int getId() { 27 return id; 28 } 29 30 public void setId(int id) { 31 this.id = id; 32 } 33 34 public String getName() { 35 return name; 36 } 37 38 public void setName(String name) { 39 this.name = name; 40 } 41 42 public float getMoney() { 43 return money; 44 } 45 46 public void setMoney(float money) { 47 this.money = money; 48 } 49 50 public Date getJobtime() { 51 return jobtime; 52 } 53 54 public void setJobtime(Date jobtime) { 55 this.jobtime = jobtime; 56 } 57 58 public Student() { 59 super(); 60 } 61 62 }
5、写StudentMapper.java及StudentMapper.xml
1) StudentMapper.java
1 package com.hw.mapper; 2 3 import java.util.List; 4 5 import com.hw.entity.Student; 6 7 public interface StudentMapper { 8 9 public void addStudent(Student stu); 10 11 public void updateStudent(Student stu); 12 13 public void delStudent(int id); 14 15 public void delAllStudent(String id); 16 17 18 public List<Student> listAll(); 19 public int getCount(); 20 21 22 public List<Student> listLikeAll(String name); 23 public int getLikeCount(String name); 24 25 26 public List<Student> listPage(int currentPage,int pageSize); 27 28 public List<Student> listLikePage(int currentPage,int pageSize,String name); 29 30 public Student getStudent(int id); 31 32 }
2) StudentMapper.xml
1 <?xml version="1.0" encoding="UTF-8" ?><!-- 相当于实现dao中的接口 --> 2 <!DOCTYPE mapper 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 5 <!-- namespace如果和spring整合时要用接口全类名,不整合任意名,id要用接口中的方法名 --> 6 <mapper namespace="com.hw.mapper.StudentMapper"> 7 8 9 <resultMap type="com.hw.entity.Student" id="stuinfo"><!-- 如果不用resultMap则不写 --> 10 <result column="id" property="id" /> 11 <result column="name" property="name" /> 12 <result column="money" property="money" /> 13 <result column="jobtime" property="jobtime" javaType="java.sql.Date" jdbcType="DATE" /> 14 </resultMap> 15 16 17 <!-- parameterType参数类型,parameterMap参数集合,id要用接口中的方法名 --> 18 <!-- 插入数据 --> 19 <insert id="addStudent" parameterType="com.hw.entity.Student"> 20 insert into stu values(null,#{name},#{money},#{jobtime}) 21 </insert> 22 23 <!-- 删除数据 --> 24 <delete id="delStudent" parameterType="int"> 25 delete from stu where id=#{id} 26 </delete> 27 28 <!-- 批量删除数据 --> 29 <delete id="delAllStudent" parameterType="int"> 30 delete from stu where id in 31 <foreach collection="array" item="id" index="0" open="(" separator="," close=")"> 32 #{id} 33 </foreach><!--item迭代时的别名open以什么开始,close以什么结束,separator符号作为分隔符 --> 34 </delete> 35 36 <!-- 查询所有 --> 37 <select id="listAll" resultMap="stuinfo"> 38 select * from stu 39 </select> 40 41 42 <!-- 查询所有记录条数 --> 43 <!-- resultType 返回结果类型 ,resultMap返回的map类型 --> 44 <select id="getCount" resultType="int"> 45 select count(id) from stu 46 </select> 47 48 <!-- 模糊查询 --> 49 <select id="listLikeAll" resultMap="stuinfo" parameterType="string"> 50 <!-- select * from stu where name like '%${value}%' --> 51 select * from stu where name like #{name} 52 </select> 53 54 55 <!-- 根据ID查询 --> 56 <select id="getStudent" resultMap="stuinfo"> 57 select * from stu where id=#{id} 58 </select> 59 60 61 <!-- 模糊查询查询记录条数 --> 62 <select id="getLikeCount" resultType="int"> 63 select count(id) from stu where name like '%${value}%' 64 </select> 65 66 67 <!-- 修改数据 --> 68 <update id="updateStudent" parameterType="com.hw.entity.Student"> 69 update stu set name=#{name},money=#{money},jobtime=#{jobtime} where id=#{id} 70 </update> 71 72 73 <!-- 分页查询所有 --> 74 <select id="listPage" resultMap="stuinfo" parameterType="map"> 75 select * from stu limit #{currentPage},#{pageSize} 76 </select> 77 78 79 <!-- 模糊分页查询所有 --> 80 <select id="listLikePage" resultMap="stuinfo" parameterType="map"> 81 <!-- select * from stu where name like '%${value}%' limit #{currentPage},#{pageSize} --> 82 select * from stu where name like #{name} limit #{currentPage},#{pageSize} 83 </select> 84 85 86 </mapper>
6、测试
测试 Test1:
1 package com.hw.test; 2 3 import java.io.IOException; 4 import java.io.Reader; 5 import java.util.List; 6 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 12 import com.hw.entity.Student; 13 14 15 16 public class Test1 { 17 18 public static void main(String[] args) throws IOException { 19 20 //读取mybatis配置文件 21 Reader read = Resources.getResourceAsReader("mybatis-config.xml"); 22 23 //创建工厂模式SqlSessionFactory 24 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(read); 25 26 //创建sqlSession 27 SqlSession sqlSession = sqlSessionFactory.openSession(); 28 29 //查询所有======================================================================================= 30 List<Student> selectList = sqlSession.selectList("listAll"); 31 for(Student ss:selectList){ 32 System.out.println(ss.getId()+"\t"+ss.getName()+"\t"+ss.getMoney()+"\t"+ss.getJobtime()); 33 } 34 35 36 //查询所有记录条数 ================================================================================ 37 int selectOne = sqlSession.selectOne("getCount"); 38 System.out.println("查询所有记录条数,共有记录 "+selectOne+" 条"); 39 40 41 //模糊查询======================================================================================= 42 // #{name} 对应 selectList("getLikeCount", "%李%"); 43 //'%${value}%' 对应 selectList("getLikeCount", "李"); 44 List<Student> selectList2 = sqlSession.selectList("listLikeAll","%李%"); 45 if(selectList2.size()>0){ 46 for(Student s1:selectList2){ 47 System.out.println(s1.getId()+"\t"+s1.getName()+"\t"+s1.getMoney()+"\t"+s1.getJobtime()); 48 } 49 }else{ 50 System.out.println("查无此人!"); 51 } 52 53 54 //模糊查询记录条数=================================================================================== 55 int selectOne2 = sqlSession.selectOne("getLikeCount","李"); 56 System.out.println("模糊查询记录条数,共有记录 "+selectOne2+" 条"); 57 58 59 //根据id查询======================================================================================= 60 System.out.println("根据ID查询"); 61 Student s2 = sqlSession.selectOne("getStudent",3);// 结果唯一 62 if(s2==null){ 63 System.out.println("查无此人!"); 64 }else{ 65 System.out.println(s2.getId()+"\t"+s2.getName()+"\t"+s2.getMoney()+"\t"+s2.getJobtime()); 66 } 67 68 } 69 }
测试 Test2:
1 package com.hw.test; 2 3 import java.io.IOException; 4 import java.io.Reader; 5 import java.text.ParseException; 6 import java.text.SimpleDateFormat; 7 import java.util.List; 8 9 import org.apache.ibatis.io.Resources; 10 import org.apache.ibatis.session.SqlSession; 11 import org.apache.ibatis.session.SqlSessionFactory; 12 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 13 14 import com.hw.entity.Student; 15 16 public class Test2 { 17 18 public static void main(String[] args) throws IOException, ParseException { 19 20 // 读取mybatis配置文件 21 Reader read = Resources.getResourceAsReader("mybatis-config.xml"); 22 23 // 创建工厂模式SqlSessionFactory 24 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(read); 25 26 // 创建sqlSession 27 SqlSession sqlSession = sqlSessionFactory.openSession(); 28 29 // 插入数据======================================================================================= 30 /*SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); 31 Student stu = new Student("迪丽热巴", 8888, sd.parse("2010-01-01")); 32 int a = sqlSession.insert("addStudent", stu); 33 if (a > 0) { 34 System.out.println("添加成功!!"); 35 } else { 36 System.out.println("添加失败!!"); 37 } 38 sqlSession.commit();// 进行事务提交,除了查询外都要加事务 39 */ 40 41 // 修改数据======================================================================================= 42 /*SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd"); 43 Student stu2 = new Student(6,"迪丽热巴1", 8866, sd.parse("2012-01-01")); 44 int b = sqlSession.update("updateStudent", stu2); 45 if (b > 0) { 46 System.out.println("修改成功!!"); 47 } else { 48 System.out.println("修改失败!!"); 49 } 50 sqlSession.commit();// 进行事务提交,除了查询外都要加事务 51 */ 52 53 // 删除数据======================================================================================= 54 /*int c = sqlSession.delete("delStudent",6); 55 if (c > 0) { 56 System.out.println("删除成功!!"); 57 } else { 58 System.out.println("删除失败!!"); 59 } 60 sqlSession.commit();// 进行事务提交,除了查询外都要加事务 61 */ 62 // 批量删除数据======================================================================================= 63 String aa = "8,9,10"; 64 String[] split = aa.split(","); 65 int deleteAll = sqlSession.delete("delAllStudent",split); 66 if (deleteAll > 0) { 67 System.out.println("批量删除成功!!"); 68 } else { 69 System.out.println("批量删除失败!!"); 70 } 71 sqlSession.commit();// 进行事务提交,除了查询外都要加事务 72 73 74 // 查询所有======================================================================================= 75 List<Student> selectList = sqlSession.selectList("listAll"); 76 for (Student ss : selectList) { 77 System.out.println(ss.getId() + "\t" + ss.getName() + "\t" + ss.getMoney() + "\t" + ss.getJobtime()); 78 } 79 } 80 }
测试 Test3:
1 package com.hw.test; 2 3 import java.io.IOException; 4 import java.io.Reader; 5 import java.text.ParseException; 6 import java.text.SimpleDateFormat; 7 import java.util.HashMap; 8 import java.util.List; 9 import java.util.Map; 10 11 import org.apache.ibatis.io.Resources; 12 import org.apache.ibatis.session.SqlSession; 13 import org.apache.ibatis.session.SqlSessionFactory; 14 import org.apache.ibatis.session.SqlSessionFactoryBuilder; 15 16 import com.hw.entity.Student; 17 18 public class Test3 { 19 20 public static void main(String[] args) throws IOException, ParseException { 21 22 // 读取mybatis配置文件 23 Reader read = Resources.getResourceAsReader("mybatis-config.xml"); 24 25 // 创建工厂模式SqlSessionFactory 26 SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(read); 27 28 // 创建sqlSession 29 SqlSession sqlSession = sqlSessionFactory.openSession(); 30 31 // 分页查询所有======================================================================================= 32 /* int currentPage = 1; 33 int pageSize = 2; 34 Map<String, Object> map = new HashMap<String, Object>(); 35 map.put("currentPage", (currentPage - 1) * pageSize); 36 map.put("pageSize", pageSize); 37 List<Student> selectList2 = sqlSession.selectList("listPage",map); 38 for (Student ss : selectList2) { 39 System.out.println(ss.getId() + "\t" + ss.getName() + "\t" + ss.getMoney() + "\t" + ss.getJobtime()); 40 }*/ 41 42 // 模糊分页查询所有======================================================================================= 43 int currentPage = 1; 44 int pageSize = 2; 45 Map<String, Object> map = new HashMap<String, Object>(); 46 map.put("name", "%李%"); 47 map.put("currentPage", (currentPage - 1) * pageSize); 48 map.put("pageSize", pageSize); 49 List<Student> selectList = sqlSession.selectList("listLikePage",map); 50 for (Student s1 : selectList) { 51 System.out.println(s1.getId() + "\t" + s1.getName() + "\t" + s1.getMoney() + "\t" + s1.getJobtime()); 52 } 53 } 54 }
代码下载:http://pan.baidu.com/s/1jIzBXhs
推荐博客:http://blog.csdn.net/jiuqiyuliang/article/details/45286191
END!!!