MyBatis基础(一)

MyBatis基础(一)

MyBatis入门

简介

(1)介绍
1、MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
2、是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)
(2)特点
1、MyBatis是一个ORM框架,可以简化JDBC操作,实现数据的持久化 。
2、解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
3、提供映射标签,支持对象与数据库的ORM字段关系映射
4、提供对象关系映射标签,支持对象关系组建维护
5、提供xml标签,支持编写动态sql。
(3)ORM概念
1、ORM: Object Relational Mapping(对象关系映射)。
2、Mybatis是ORM的一个实现,orm可以让开发人员  像操作对象一样 操作数据库表。
3、ORM的实现:MyBatis、Hibernate、JPA等。

开发步骤(以查询为例)

  • 创建数据库和表

  • 把需要的jar包(mybatis-3.4.6.jar 数据库驱动jar包)添加到项目的类路径中

  • 配置mybatis,conf.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的 id 来指定 MyBatis运行时的数据库环境-->
    	<environments default="development">
            
            <!-- 配置一个运行环境 -->
    		<environment id="development">
            	<!-- 事务提交方式:
    				JDBC:利用JDBC方式处理事务(commit  rollback  close)
    				MANAGED:将事务交由 其他组件去托管(spring ,jboss),默认 会关闭连接。
    			
    			<transactionManager type="MANAGED"/>
    				closeConnection为:false,不关闭连接
    				<property name="closeConnection" value="false"/>
    			 -->
            <!-- 事务处理方式:jdbc方式,即:手动处理 -->
    		<transactionManager type="JDBC"/>
                
                <!-- 数据源类型:
    					UNPOOLED:不使用数据库连接池,传统的JDBC模式(每次访问数据库,均需要 打开、关闭等数据库操作,但是 打开、关闭数据库是比较消耗性能的)
    					POOLED:使用第三方数据库连接池
    					JNDI:从tomcat中获取一个内置的数据库连接池 (数据库连接池-数据源  )
    			-->
                <!-- 数据源: 第三方数据库连接池 -->
    			<dataSource type="POOLED">
                
    			<!-- 配置数据库信息 -->
    			<property name="driver" value="oracle.jdbc.OracleDriver"/>
    			<property name="url" 		   value="jdbc:oracle:thin:@127.0.0.1:1521:ORCL"/>
    			<property name="username" value="scott"/>
    			<property name="password" value="tiger"/>
    		</dataSource>
    		</environment>
    	</environments>
        
    	<mappers>
    		<!-- 加载映射文件 -->
    		<mapper resource="org/lanqiao/entity/personMapper.xml"/>
    	</mappers>
    </configuration>
    
  • 编写数据库表对应的实体类,即:表 - 类

    public class Person {
    	private int id;
    	private String name;
    	private int age ;
    	
    	public Person() {
    	}
    	public Person(int id, String name, int age) {
    		this.id = id;
    		this.name = name;
    		this.age = age;
    	}
    	public int getId() {
    		return id;
    	}
    	public void setId(int id) {
    		this.id = id;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public int getAge() {
    		return age;
    	}
    	public void setAge(int age) {
    		this.age = age;
    	} 
    	
    	@Override
    	public String toString() {
    		return this.id+","+this.name+","+this.age ;
    	}
    }
    
  • 实体类和数据库表的关系的映射文件:xxMapper.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="org.lanqiao.entity.Person">
    	<select id="queryPersonById" resultType="org.lanqiao.entity.Person"  parameterType="int">
    		select * from person where  id = #{id} 
    	</select>
    </mapper>
    
    • 小结

      1、namespace: 该映射文件的全路径名,可以理解为该Mapper.xml文件的唯一标识符。
      2、select: 表示该SQL语句是查询的SQL。
      	除此之外,还有: insert、delete、update。
      3、id: 该SQL语句的唯一标识符,在该Mapper文件中必须唯一,命名如: queryPersonById。
      4、resultType: 该SQL语句的结果返回值类型,也是全类名。
      5、parameterType: 参数类型,如该SQL有参数,该属性就是指定参数类型的。
      6、#{参数名}: 用于接收参数,参数名可以随便起,但建议见名知意。(#{id}:占位符) 
      7、SQL语句结束(末尾)没有分号。
      
  • 编写测试类

    public class TestMyBatis {
    	public static void main(String[] args) throws IOException {
    		//加载MyBatis配置文件(为了访问数据库),conf.xml --> reader 
    		Reader reader = Resources.getResourceAsReader("conf.xml") ;
            
            //reader --> SqlSession
            //创建一个SqlSessionFactoryr对象(SQL会话工厂对象)
    		SqlSessionFactory sessionFactory = new 		       SqlSessionFactoryBuilder().build(reader) ;
    		//session - connection: 打开会话
    		SqlSession session = sessionFactory.openSession() ;
            //namespace.id
    		String statement = "org.lanqiao.entity.Person.queryPersonById" ;
            //执行SQL
            //session.selectOne("需要查询的SQL的namespace.id","SQL的参数值");
      	Person person = session.selectOne( statement,1 ) ;
    		System.out.println(person);
          //关闭会话(连接)
    		session.close(); 
    	}
    }
    

增加数据

  • studentMapper.xml

    <!-- namespace:该mapper.xml映射文件的 唯一标识 -->
    <mapper namespace="org.lanqiao.entity.Student">
    	<!-- parameterType:输入参数的类型 -->	
    	<insert id="addStudent" parameterType="org.lanqiao.entity.Student" >
    		insert into student(stuno,stuname,stuage,graname) values(#{stuNo},#{stuName},#{stuAge},#{graName}  ) 
    	</insert>
    </mapper>
    
    • 小结

      mybatis约定:
      1、输入参数parameterType 和 输出参数resultType ,在形式上都只能有一个
      如果输入参数:是简单类型(8个基本类型+String) 是可以使用任何占位符,#{xxxx}
      	       如果是对象类型,则必须是对象的属性 #{属性名}
      
      输出参数:如果返回值类型是一个对象(如Student),则无论返回一个、还是多个,
      		在resultType都写成org.lanqiao.entity.Student
      		即 resultType="org.lanqiao.entity.Student"
      
  • StudentTest.java

     //增加学生
    public static void addStudent() throws IOException {
     	//Connection -  SqlSession操作MyBatis
        //conf.xml - > reader
        Reader reader = Resources.getResourceAsReader("conf.xml") ;
        
        //reader -> SqlSession
        //可以通过build的第二参数 指定数据库环境
    	SqlSessionFactory sessionFacotry = new SqlSessionFactoryBuilder().build(reader,"development") ;
        SqlSession session = sessionFacotry.openSession() ;
    
        //namespace.id
        String statement = "org.lanqiao.entity.Student."+"addStudent";
        Student student = new Student(3,"ww",25,"s1");
        int count = session.insert(statement, student );//statement:指定执行的SQL student:sql中需要的参数 ( ? ? ? )
        session.commit(); //提交事务
        System.out.println("增加" + count + "个学生");
        session.close();
    }
    

    注意事项:
    如果使用的 事务方式为 jdbc,进行增删改操作时,需要 手工commit提交,即 session.commit();

删除数据

  • studentMapper.xml

    <mapper namespace="org.lanqiao.entity.Student">
    	<!-- parameterType:输入参数的类型 -->	
    	<delete id="deleteStudentByStuno"  parameterType="int">
    		delete from student where stuno = #{stuno} 
    	</delete>
    </mapper>
    
  • StudentTest.java

     //删除学生
    public static void delteStudentByStuno() throws IOException {
        //Connection -  SqlSession操作MyBatis
        //conf.xml - > reader
        Reader reader = Resources.getResourceAsReader("conf.xml") ;
        //reader  ->SqlSession
        //可以通过build的第二参数 指定数据库环境
        SqlSessionFactory sessionFacotry = new SqlSessionFactoryBuilder().build(reader,"development") ;
        SqlSession session = sessionFacotry.openSession() ;
    
        String statement = "org.lanqiao.entity.Student."+"deleteStudentByStuno";
        
        int count = session.delete(statement,3) ;
    
        session.commit(); //提交事务
    
        System.out.println("删除"+count+"个学生");
        session.close();
    }
    

修改数据

  • studentMapper.xml

    <mapper namespace="org.lanqiao.entity.Student">
    	<!-- parameterType: 输入参数的类型 -->	
    	<update id="updateStudentByStuno" parameterType="org.lanqiao.entity.Student" >
    		update student set stuname=#{stuName} ,stuage=#{stuAge},graname=#{graName} where stuno=#{stuNo} 
    	</update>
    </mapper>
    
  • StudentTest.java

    //修改学生
    public static void updateStudentByStuno() throws IOException {
        //Connection -  SqlSession操作MyBatis
        //conf.xml - > reader
        Reader reader = Resources.getResourceAsReader("conf.xml") ;
        //reader  ->SqlSession
        //可以通过build的第二参数 指定数据库环境
        SqlSessionFactory sessionFacotry = new SqlSessionFactoryBuilder().build(reader,"development") ;
        SqlSession session = sessionFacotry.openSession() ;
    
        String statement = "org.lanqiao.entity.studentMapper."+"updateStudentByStuno";
        //修改的参数
        Student student = new Student();
        //修改哪个人,where stuno =2 
        student.setStuNo(2);
        //修改成什么样子?
        student.setStuName("lxs");
        student.setStuAge(44);
        student.setGraName("s2");
        //执行
        int count = session.update(statement,student) ;
    
        session.commit(); //提交事务
    
        System.out.println("修改"+count+"个学生");
        session.close();
    }
    

查询多条数据

  • studentMapper.xml

    <mapper namespace="org.lanqiao.entity.studentMapper">
    	<!-- parameterType: 输入参数的类型 -->	
    	<select id="queryAllStudents"  resultType="org.lanqiao.entity.Student" >
    		select * from student 
    	</select>
    </mapper>
    
    • 小结

      输出参数:如果返回值类型是一个对象(如Student),则无论返回一个、还是多个,
      		在resultType都写成org.lanqiao.entity.Student
      		即 resultType="org.lanqiao.entity.Student"
      
  • StudentTest.java

    //查询全部学生
    public static void queryAllStudents() throws IOException {
        //Connection -  SqlSession操作MyBatis
        //conf.xml - > reader
        Reader reader = Resources.getResourceAsReader("conf.xml") ;
        //reader  ->SqlSession
        //可以通过build的第二参数 指定数据库环境
        SqlSessionFactory sessionFacotry = new SqlSessionFactoryBuilder().build(reader,"development") ;
        SqlSession session = sessionFacotry.openSession() ;
    
        String statement = "org.lanqiao.entity.studentMapper."+"queryAllStudents";
        List<Student> students = session.selectList(statement) ;
        System.out.println(students);
        session.close();
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

sunnyboy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值