MyBatis的一个入门程序

MyBatis在操作数据库时,主要分为8大步骤:

(1) 读取MyBatis配置文件mabatis-config.xml,mabatis-config.xml作为MaBatis的全局配置文件,配置了MyBatis的运行环境等信息,其主要是获取数据库连接。

(2) 加载映射文件Mapper.xml。Mapper.xml即SQL映射文件,该文件配置了操作数据库的SQL语句,需要在mybatis-config.xml中加载才能执行。mybatis-config.xml可以添加多个配置文件,每个配置文件对应数据库中的一张表。

(3) 构建会话工厂。通过MyBatis的环境等配置信息构建会话工厂SqlSessionFactory。

(4) 创建SqlSession对象。由会话工厂创建SqlSession对象。,该对象中包含执行SQL的所有方法。

(5) MyBatis底层定义的一个Executor接口会根据SqlSession传递的参数动态生成SQL语句,同时负责查询缓存的维护。

(6) 根据生成的SQL语句生成MappedStatement对象。

(7) 向MappedStatement输入映射对象,这里的输入参数的映射过程就相当于JDBC编程中对preparedStatement对象设置参数的过程。

(8) 执行SQL语句,对MappedStatement对象返回的结果进行处理。

下面通过一个入门程序来理解。

1.根据学号查询学生信息

(1)这里用sql server数据库。

在SQL Server数据库中,创建一个名为student的数据库,创建一个student表,并插入几条数据。

创建代码:


 
 
  1. create database student;
  2. use student;
  3. create table student
  4. (
  5. st_no int identity( 1, 1) primary key ,
  6. st_name varchar( 30) not null,
  7. sex varchar( 2) default '男' not null,
  8. tel varchar( 11),
  9. address varchar( 30),
  10. )
  11. alter table student add constraint ck_sex check (sex in( '男', '女'));
  12. insert into student values( '张三', '女', '13688883333', '湖南长沙');
  13. insert into student values( '李四', '女', '13644443333', '湖南益阳');
  14. insert into student values( '李元霸', '男', '13512222444', '湖南衡阳');
  15. insert into student values( '张莉莉', '女', '13688883333', '湖南长沙');
  16. select * from student;

(2)在Myeclipse创建一个名为project01的Web项目,将MyBatis的核心jar包、依赖包,以及Sql Server数据库驱动添加到项目的lib目录下。

(3)在src目录下创建log4j.properties文件,内容如下 :


 
 
  1. # Global logging configuration
  2. log4j.rootLogger=ERROR, stdout
  3. # MyBatis logging configuration...
  4. log4j.logger.cn.swjd=DEBUG
  5. # Console output...
  6. log4j.appender.stdout=org.apache.log4j.ConsoleAppender
  7. log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
  8. log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

MyBatis默认使用log4j输出日志信息,如果要在控制台查看sql语句,就必须

在src目录下创建log4j.properties文件。

(4)在src目录下创建cn.swjd.entries包,在该包下创建持久化类Student。


 
 
  1. package cn.swjd.entries;
  2. //学生持久化类
  3. public class Student {
  4. //主键学号
  5. private Integer st_no;
  6. //姓名,性别,年龄,电话 ,地址
  7. private String st_name, sex, tel, address;
  8. public Integer getSt_no() {
  9. return st_no;
  10. }
  11. public void setSt_no(Integer st_no) {
  12. this.st_no = st_no;
  13. }
  14. public String getSt_name() {
  15. return st_name;
  16. }
  17. public void setSt_name(String st_name) {
  18. this.st_name = st_name;
  19. }
  20. public String getSex() {
  21. return sex;
  22. }
  23. public void setSex(String sex) {
  24. this.sex = sex;
  25. }
  26. public String getTel() {
  27. return tel;
  28. }
  29. public void setTel(String tel) {
  30. this.tel = tel;
  31. }
  32. public String getAddress() {
  33. return address;
  34. }
  35. public void setAddress(String address) {
  36. this.address = address;
  37. }
  38. @Override
  39. public String toString() {
  40. return "Student [st_no=" + st_no + ", st_name=" + st_name + ", sex="
  41. + sex + ", tel=" + tel + ", address=" + address + "]";
  42. }
  43. }

 

(5)在src目录下。创建cn.swjd.mapper包,在包里创建映射文件StudentMapper.xml。


 
 
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="cn.swjd.mapper.StudentMapper">
  5. <select id="findStudentById" parameterType="Integer" resultType="cn.swjd.entries.Student">
  6. select * from student where st_no= #{st_no}
  7. </select>
  8. </mapper>

说明:<mapper>元素是配置文件的根元素,它包含一个namespace属性,该属性指定了<mapper>的唯一命名空间,通常设置为“包名+SQL映射文件名”的形式。

子元素<select>中的信息是用于执行查询操作的配置,id是唯一标识符。

parameterType:指定传入参数的类型。

resultType:指定返回结果的类型。

#{}:表示一个占位符,相当于jdbc中的?,其里面的内容为接受参数的名称。

 (6)在src目录下,创建MyBatis的核心配置文件mybatis-config.xml。


 
 
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">
  4. <configuration>
  5. <environments default="sqlserver">
  6. <environment id="sqlserver">
  7. <transactionManager type="JDBC"/>
  8. <!-- 配置数据库连接池 -->
  9. <dataSource type="POOLED">
  10. <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>
  11. <property name="url" value="jdbc:sqlserver://localhost:1433;DataBaseName=student"/>
  12. <property name="username" value="sa"/>
  13. <property name="password" value="123"/>
  14. </dataSource>
  15. </environment>
  16. </environments>
  17. <mappers>
  18. <mapper resource="cn/swjd/mapper/StudentMapper.xml"/>
  19. </mappers> </configuration>

说明:

  <environments>下可配置多个运行环境,default属性用于设置默认运行环境。

(7)在src目录下,创建一个cn.swjd.test包,创建测试类MyBatisTest,再编写一个方法findStudentByIdTest(int st_id),并在main方法里调用。


 
 
  1. package cn.swjd.test;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import org.apache.ibatis.io.Resources;
  5. import org.apache.ibatis.session.SqlSession;
  6. import org.apache.ibatis.session.SqlSessionFactory;
  7. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  8. import cn.swjd.entries.Student;
  9. public class MyBatisTest {
  10. public static void findStudentByIdTest(int st_id) throws Exception{
  11. //1.读取配置文件
  12. String resource= "mybatis-config.xml";
  13. InputStream inputstream=Resources.getResourceAsStream(resource);
  14. //2.根据配置文件构建SqlSessionFactory
  15. SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(inputstream);
  16. //3.通过SqlSessionFactory构建SqlSession
  17. SqlSession sqlsession=factory.openSession();
  18. //4.SqlSession执行映射文件中定义的SQL,并返回其映射结果
  19. Student s=sqlsession.selectOne( "cn.swjd.mapper.StudentMapper.findStudentById",st_id);
  20. //打印输出结果
  21. System.out.println(s.toString());
  22. }
  23. public static void main(String args[]) throws Exception{
  24. findStudentByIdTest( 1);
  25. }
  26. }

 

运行结果:

2.根据姓名模糊查询学生信息

修改映射文件StudentMapper.xml,添加一个<select>

<select id="findStudentByName" parameterType="String" resultType="cn.swjd.entries.Student">

      select * from student where st_name like '%${value}%' 

      </select>

这里传入参数为什么不设置为#{}而用${}呢?

假设传入参数在程序里为 String value=”张”;

如果使用的是#{},最终的sql语句就会变成:

select * from student where st_name like ‘’张’’ 

使用${},最终的sql语句就会变成:

select * from student where st_name like ‘张’

原因:如果使用的是#{}传入参数?就会根据配置文件<select>中parameterType属性(即数据类型)自动变换,如果parameterType="String",就会自动加入’’, 如果parameterType="Integer",就不会加’’

而使用${} 不管parameterType属性为何值,都不会自动加’’

在类MyBatisTest,编写一个方法findStudentByNameTest(String value),并在main方法里调用。


 
 
  1. public static void findStudentByNameTest(String st_name) throws Exception{
  2. //1.读取配置文件
  3. String resource= "mybatis-config.xml";
  4. InputStream inputstream=Resources.getResourceAsStream(resource);
  5. //2.根据配置文件构建SqlSessionFactory
  6. SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(inputstream);
  7. //3.通过SqlSessionFactory构建SqlSession
  8. SqlSession sqlsession=factory.openSession();
  9. //4.SqlSession执行映射文件中定义的SQL,并返回其映射结果
  10. List<Student> s=sqlsession.selectList( "cn.swjd.mapper.StudentMapper.findStudentByName",st_name);
  11. /*selectList方法第一个参数为<Mapper>的namespace属性+<select>的id属性,后面接传入参数*/
  12. //打印输出结果
  13. for(Student stu:s)
  14. System.out.println(stu.toString());
  15. }
  16. public static void main(String args[]) throws Exception{
  17. findStudentByNameTest( "张");
  18. }

运行结果: 

结果出来了,但是这里有一个问题,使用“${}”拼接字符串,无法防止sql注入问题。

比如这里,如果把方法调用改成:

findStudentByNameTest("1';delete from student where st_no>0;commit; select * from student where st_name like '”);

它竟然可以操作数据库!把表所有内容都删除了。显然,实际项目开发中,是不能出现这种bug的,你永远不知道用户会输入什么东西。

所以,为了安全性,这里不能用${},只能用#{},我们可以用SqlServer中的拼接函数concat()。

修改后:

select * from student where st_name like concat('%',#{value},'%')

 

修改、删除、增加操作都差不多

相比于查询,就是多了sqlsession.commit()提交事务这一步骤而已


 
 
  1. <?xml version="1.0" encoding="UTF-8" ?>
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  4. <mapper namespace="cn.swjd.mapper.StudentMapper">
  5. <!-- 根据学号查询学生信息 -->
  6. <select id="findStudentById" parameterType="Integer" resultType="cn.swjd.entries.Student">
  7. select * from student where st_no= #{st_no}
  8. <!-- 根据姓名模糊查询学生信息 -->
  9. </select>
  10. <select id="findStudentByName" parameterType="String" resultType="cn.swjd.entries.Student">
  11. select * from student where st_name like concat('#',#{value},'#')
  12. </select>
  13. <!-- 更新学生信息 -->
  14. <update id="updateStudent" parameterType="cn.swjd.entries.Student"
  15. >
  16. update student set st_name=#{st_name},sex=#{sex},tel=#{tel},address=#{address} where st_no=#{st_no}
  17. </update>
  18. <!-- 删除学生信息 -->
  19. <delete id="deleteStudent" parameterType="Integer">
  20. delete from student where st_no=#{id}
  21. </delete>
  22. <!-- 增加学生信息 -->
  23. <insert id="addStudent" parameterType="cn.swjd.entries.Student">
  24. insert into student values (#{st_name},#{sex},#{tel},#{address})
  25. </insert>
  26. </mapper>

 
 
  1. package cn.swjd.test;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.util.List;
  5. import org.apache.ibatis.io.Resources;
  6. import org.apache.ibatis.session.SqlSession;
  7. import org.apache.ibatis.session.SqlSessionFactory;
  8. import org.apache.ibatis.session.SqlSessionFactoryBuilder;
  9. import cn.swjd.entries.Student;
  10. public class MyBatisTest {
  11. //根据学号查找学生
  12. public static void findStudentByIdTest(int st_id) throws Exception{
  13. //1.读取配置文件
  14. String resource= "mybatis-config.xml";
  15. InputStream inputstream=Resources.getResourceAsStream(resource);
  16. //2.根据配置文件构建SqlSessionFactory
  17. SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(inputstream);
  18. //3.通过SqlSessionFactory构建SqlSession
  19. SqlSession sqlsession=factory.openSession();
  20. //4.SqlSession执行映射文件中定义的SQL,并返回其映射结果
  21. Student s=sqlsession.selectOne( "cn.swjd.mapper.StudentMapper.findStudentById",st_id);
  22. /*selectOne方法第一个参数为<Mapper>的namespace属性+<select>的id属性,后面接传入参数*/
  23. //打印输出结果
  24. System.out.println(s.toString());
  25. }
  26. //根据姓名模糊查找学生
  27. public static void findStudentByNameTest(String st_name) throws Exception{
  28. //1.读取配置文件
  29. String resource= "mybatis-config.xml";
  30. InputStream inputstream=Resources.getResourceAsStream(resource);
  31. //2.根据配置文件构建SqlSessionFactory
  32. SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(inputstream);
  33. //3.通过SqlSessionFactory构建SqlSession
  34. SqlSession sqlsession=factory.openSession();
  35. //4.SqlSession执行映射文件中定义的SQL,并返回其映射结果
  36. List<Student> s=sqlsession.selectList( "cn.swjd.mapper.StudentMapper.findStudentByName",st_name);
  37. /*selectList方法第一个参数为<Mapper>的namespace属性+<select>的id属性,后面接传入参数*/
  38. //打印输出结果
  39. for(Student stu:s)
  40. System.out.println(stu.toString());
  41. }
  42. //更新学生信息
  43. public static void updateStudent(Student s) throws IOException{
  44. //1.读取配置文件
  45. String resource= "mybatis-config.xml";
  46. InputStream inputstream=Resources.getResourceAsStream(resource);
  47. //2.根据配置文件构建SqlSessionFactory
  48. SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(inputstream);
  49. //3.通过SqlSessionFactory构建SqlSession
  50. SqlSession sqlsession=factory.openSession();
  51. //4.SqlSession执行映射文件中定义的SQL,并返回其映射结果
  52. int i = sqlsession.update( "cn.swjd.mapper.StudentMapper.updateStudent", s);
  53. //提交事务
  54. sqlsession.commit();
  55. if(i> 0){
  56. System.out.println( "更新学号为"+s.getSt_no()+ "学生信息成功!");
  57. }
  58. }
  59. //删除学生信息
  60. public static void deleteStudent(int st_no) throws IOException{
  61. //1.读取配置文件
  62. String resource= "mybatis-config.xml";
  63. InputStream inputstream=Resources.getResourceAsStream(resource);
  64. //2.根据配置文件构建SqlSessionFactory
  65. SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(inputstream);
  66. //3.通过SqlSessionFactory构建SqlSession
  67. SqlSession sqlsession=factory.openSession();
  68. //4.SqlSession执行映射文件中定义的SQL,并返回其映射结果
  69. int i = sqlsession.delete( "cn.swjd.mapper.StudentMapper.deleteStudent", st_no);
  70. //5.提交事务
  71. sqlsession.commit();
  72. if(i> 0){
  73. System.out.println( "删除学号为"+st_no+ "的学生信息成功!");
  74. }
  75. }
  76. //增加学生信息
  77. public static void addStudent(Student s) throws IOException{
  78. //1.读取配置文件
  79. String resource= "mybatis-config.xml";
  80. InputStream inputstream=Resources.getResourceAsStream(resource);
  81. //2.根据配置文件构建SqlSessionFactory
  82. SqlSessionFactory factory= new SqlSessionFactoryBuilder().build(inputstream);
  83. //3.通过SqlSessionFactory构建SqlSession
  84. SqlSession sqlsession=factory.openSession();
  85. //4.SqlSession执行映射文件中定义的SQL,并返回其映射结果
  86. int i = sqlsession.insert( "cn.swjd.mapper.StudentMapper.addStudent", s);
  87. //5.提交事务
  88. sqlsession.commit();
  89. if(i> 0){
  90. System.out.println( "添加一条学生信息成功!");
  91. }
  92. }
  93. public static void main(String args[]) throws Exception{
  94. Student s= new Student();
  95. s.setSt_name( "李云瑞");
  96. s.setSex( "男");
  97. addStudent(s);
  98. }
  99. }

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值