MyBasti使用教程(简单使用MyBasti操作数据增删改+延迟加载+联合查询)

简化jdbc操作,实现数据的持久化

MyBasti官网
http://www.mybatis.org/mybatis-3/zh/getting-started.html
简单使用MyBasti操作数据增删改
在这里插入图片描述
1.创建java项目转换meaven项目,导入pom.xml标签

  <dependencies>
    	<dependency>
	    <groupId>org.mybatis</groupId>
	    <artifactId>mybatis</artifactId>
	    <version>3.2.8</version>
	</dependency>
	
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.38</version>
	</dependency>
	
	<!-- log4j:日志文件 -->
	<dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>1.2.17</version>
	</dependency> 	
	
	<!--延时加载: https://mvnrepository.com/artifact/cglib/cglib -->
	<dependency>
	    <groupId>cglib</groupId>
	    <artifactId>cglib</artifactId>
	    <version>2.2.2</version>
	</dependency>
  </dependencies>

创建实体类Student-------------------
public class Student {
    Integer id;
    String  name;
    Integer age;
    Date    bd;
    Classes classes;
    set\get方法+构造函数

2.创建mybatis-3-config.xml
在src根目录下创建mybatis-3-config.xml 复制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">
  <!-- dtd是约束xml文件 -->
<configuration>
<!-- 链接数据库信息  通过default制定使用哪个数据库链接
也可以强行修改使用哪个
 	  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream,"svn");
 -->
  <environments default="development">
      <!-- 可创建多个数据库连接池  以id做唯一标识   -->
    <environment id="development">
        <!--事务提交方式:
        JDBC:利用JDBC方式处理事务(commit rollback close)
        MANAGED:将事务交由其他组件去托管(Spring,jobss) 
     -->
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///springjdbc"/>
        <property name="username" value="root"/>
        <property name="password" value="111"/>
      </dataSource>
    </environment>
  <!-- 项目svn数据库   -->
  <environment id="svn">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///springjdbc"/>
        <property name="username" value="root"/>
        <property name="password" value="111"/>
      </dataSource>
    </environment>
  </environments>
  <!-- 映射器  指明对数据库操作的配置文件
       com.pb.mapper把.换成/
        创建这个映射器文件
   -->
  <mappers>
    <mapper resource="com/pb/mapper/StudentMapper.xml"/>
  </mappers>
</configuration>

4.创建映射器文件xxxMapper.xml
src个根目录下创建package名为mapper

<?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">
<!-- namespace:传入接口文件 -->  
<mapper namespace="com.pb.mapper.StudentMapper">
   <!--操作sql 
       id:唯一标识
       parameterType传入的参数类型  对象写路径,其他写类型  (这里写的是别名,在mybatis-config.xml配置)
       resultType返回值类型
        标签中间写sql语句  占位符#{属性名/对象属性值}
        
    -->
    <!--添加数据后展示添加的id  只适用于mysql  sql有自增功能的数据库
       useGeneratedKeys:获取自增的主键赋值给keyProperty,该属性只对insert语句有效
       keyProperty:指明赋值的属性名字
    
      -->
   <insert id="insertStuden" parameterType="Student" useGeneratedKeys="true" keyProperty="id" >
         insert into Student(stuname,age,brithday) values (#{name},#{age},#{bd})
   </insert>
<!--  
             select * from Student where id=#{id}	
     
			 输出:2-null-14-null
               因为表字段名与实体类属性名不一致导致不能正确的映射  
                           
                              实体类                      Mysql         赋值
            Integer id;          id           2
		    String  name;        stuname      null
		    Integer age;         age          14
		    Date    bd;          brithday     null
		使用别名处理>>>>>>>>>>>>>>>>>>>>>>>不推荐
		select id id,stuname name,age age,brithday bd from Student where id=#{id}
		    
-->
   <select id="findById" parameterType="int" resultType="Student">
		select id id,stuname name,age age,brithday bd from Student where id=#{id}	
   </select>
      
      
      
      
<!-- 
         创建类与查询结果的映射:定义查询结果与类之间的映射关系,列名与属性名之间对应关系
     type:对应类型
     id:以xxxxResultMapper命名
     
        主键方式:<id column="表里列名"  property="实体类属性名"/>
      其 他 列 :<result  column="表里列名"  property="实体类属性名"/>
-->
      <resultMap type="Student" id="StudentResultMapper">
          <id column="id"  property="id"/>
          <result  column="stuname"  property="name"/>
          <result  column="age"  property="age"/>
          <result  column="brithday"  property="bd"/>
      </resultMap>
      <!-- 使用结果映射 -->
      <select id="findById2" parameterType="int" resultMap="StudentResultMapper">
        select * from Student where id=#{id}
      </select>
      
      <update id="updateStudent" parameterType="Student">
        update Student set stuname=#{name},age=#{age}, brithday=#{bd} where id=#{id}
      </update>
      
      <delete id="deleteStudent" parameterType="int">
        delete from Student where id=#{id}
      </delete>
      
      <select id="selectAll" resultMap="StudentResultMapper">
           select * from Student 
      </select>    
      
      <!--动态sql  在sql语句里添加循环遍历 -->
      <select id="findByProperty" parameterType="Student" resultMap="StudentResultMapper">
           select * from Student where 1=1
           <if test="name!=null and name!=''">
               and stuname like concat("%",#{name},"%")
           </if>
      </select>
</mapper>

根据StudentMapper创建接口文件

public interface StudentMapper {
      void insertStuden(Student student);
      Student findById(int id);
      Student findById2(int id);
      List<Student>  selectAll();
      void updateStudent(Student student);
      void deleteStudent(int id);
      List<Student> findByProperty(Student student);
}

5.测试类

  public static void main(String[] args) {
	  SqlSession session= null;
	  
	try {
		  String resource = "mybatis-config.xml";
		  InputStream 	inputStream = Resources.getResourceAsStream(resource);
		  SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
          session=sqlSessionFactory.openSession();
          //开启后需要关闭
          Student student2=new Student(1,"n", 36, new Date());
/* 增删改打点出接口方法
session.getMapper(StudentMapper.class).deleteStudent(2);
*/   
//模糊联合查       
          List<Student> students=session.getMapper(StudentMapper.class).findByProperty(student2);
          for(Student student:students) {
        	  System.out.println(student.getId()+"-"+student.getName()+"-"+student.getAge()+"-"+student.getBd());   
          }
          //添加增删改的事务提交,不写的话即使sql语句正确但是信息不会被更改,并且自增列会自动自增
          session.commit();
	} catch (IOException e) {
		e.printStackTrace();
	}finally {
		session.close();
	}
}

延迟加载+联合查询

<?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">
<!-- namespace:传入接口文件 -->  
<mapper namespace="com.pb.mapper.StudentMapper">

    <!--添加数据后展示添加的id
       useGeneratedKeys:获取自增的主键赋值给keyProperty,该属性只对insert语句有效
       keyProperty:指明赋值的属性名字
       <insert id="insertStuden" parameterType="Student" useGeneratedKeys="true" keyProperty="id" >
         insert into Student(stuname,age,brithday) values (#{name},#{age},#{bd})
   </insert>
      -->

       
<!-- 
创建类与查询结果的映射:定义查询结果与类之间的映射关系,列名与属性名之间对应关系
type:对应类型
id:以xxxxResultMapper命名
     
主键方式:<id column="表里列名"  property="实体类属性名"/>
其 他 列 :<result  column="表里列名"  property="实体类属性名"/>
<association property="对应类的属性名classes"  
             javaType="对应的java类别名Classes" 
             column="数据库对应的列class" 
             select="写一个查询的方法findClassById  用于2条语句联合查 " 
             resultMap="对应的结果集合  用于一条语句联合查">  
</association>
使用findClassById查询classes对象结果赋值给association标签
 
-->
      <resultMap type="Student" id="StudentResultMapper">
          <id column="id"  property="id"/>
          <result  column="stuname"  property="name"/>
          <result  column="age"  property="age"/>
          <result  column="brithday"  property="bd"/>
          <!-- 
           <association property="classes"  javaType="Classes" column="class_id" select="findClassById"></association>
        
           -->
           <association property="classes"  javaType="Classes" column="class_id" resultMap="ClassesResultMapper"></association>
    
   
      </resultMap>
      
      <resultMap type="Classes" id="ClassesResultMapper">
            <id column="class_id"  property="id"/>
            <result  column="class_name"  property="name" />
      </resultMap>

      <select id="findStudentById" parameterType="int" resultMap="StudentResultMapper">
           select * from Student where id=#{id}
      </select>
      
      <select id="findClassById" parameterType="int" resultMap="ClassesResultMapper">
           select * from class where  class_id=#{id}
      </select>
      <!-- 联合查询 -->
      <select id="findByJoin" parameterType="int" resultMap="StudentResultMapper">
			SELECT s.*,c.* FROM student s JOIN `class` c ON s.`class_id` =c.`class_id` WHERE id=#{id}
      </select>
</mapper>

在使用语句执行时结果为
Student stu=session.getMapper(StudentMapper.class).findStudentById(3);
System.out.println(stu.getName()+"-"+stu.getAge());
System.out.println(stu.getClasses());

12:00:24,492 DEBUG JdbcTransaction:98 - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@66a3ffec]
12:00:24,494 DEBUG findStudentById:139 - ==>  Preparing: select * from Student where id=? 
12:00:24,510 DEBUG findStudentById:139 - ==> Parameters: 3(Integer)
12:00:24,524 DEBUG findClassById:139 - ====>  Preparing: select * from class where class_id=? 
12:00:24,524 DEBUG findClassById:139 - ====> Parameters: 1(Integer)
12:00:24,525 DEBUG findClassById:139 - <====      Total: 1
12:00:24,525 DEBUG findStudentById:139 - <==      Total: 1
xiaoming-13
com.pb.entity.Classes@271053e1

从日志文件看出 语句是全部执行完后再输出结果,即使只输出一个结果2条查询语句也会照样执行,
而在使用延时加载后

12:03:59,173 DEBUG JdbcTransaction:98 - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@6a4f787b]
12:03:59,174 DEBUG findStudentById:139 - ==>  Preparing: select * from Student where id=? 
12:03:59,191 DEBUG findStudentById:139 - ==> Parameters: 3(Integer)
12:03:59,250 DEBUG findStudentById:139 - <==      Total: 1
xiaoming-13 ------------------执行的第一条
12:03:59,251 DEBUG findClassById:139 - ==>  Preparing: select * from class where class_id=? 
12:03:59,251 DEBUG findClassById:139 - ==> Parameters: 1(Integer)
12:03:59,251 DEBUG findClassById:139 - <==      Total: 1
com.pb.entity.Classes@1a1d6a08-----执行的第二条

我们可以看出是执行一条查询语句后输出输出相应的语句 而在执行1条输出语句时会自动的执行相应的查询语句

---------------------------联合查询
联合查询我们分为2种模式
many2one 多对一 如多个学生对应1个班级 购物车商品列表对应1个user
one2many 一对多 如一个班级对应多个学生 1个user对应有多个购物车商品

联合查询对象

<association property="对应类的属性名classes"  
         javaType="对应的java类别名Classes" 
         column="数据库对应的列class" 
         select="写一个查询的方法findClassById  用于2条语句联合查 " 
         resultMap="对应的结果集合  用于一条语句联合查">  
 </association>

根据查询findStudentById语句中的class_id值查询findClassById返回结果 javaType="Classes"类型 >赋值给Student的classes属性 调用1个方法执行2句

  <association property="classes"  javaType="Classes" column="class_id" select="findClassById">   </association>
  <select id="findStudentById" parameterType="int" resultMap="StudentResultMapper">
       select * from Student where id=#{id}
  </select>
  
  <select id="findClassById" parameterType="int" resultMap="ClassesResultMapper">
       select * from class where  class_id=#{id}
  </select>

调用findByJoin方法查询student+class 返回StudentResultMapper(也就是Student),其中property="classes"属性是联合查询中返回的resultMap="ClassesResultMapper"类的集合

  <association property="classes"  javaType="Classes" column="class_id" resultMap="ClassesResultMapper"></association>
  <select id="findByJoin" parameterType="int" resultMap="StudentResultMapper">
		SELECT s.*,c.* FROM student s JOIN `class` c ON s.`class_id` =c.`class_id` WHERE id=#{id}
  </select>

one2many 模式 从班级角度去看学生:一个班级包含多个学生 我们从classes写代码
在classes类中添加Student集合

   public class Classes {
   Integer id;
   String  name;
   List<Student> student=new ArrayList<>();
   set\get方法....

修改config的映射器代码

       <mappers>
  		  <mapper resource="com/pb/mapper/ClassesMapper.xml"/>
       </mappers>

Classesmapper.xml文件

public interface ClassesMapper {
    Classes findByClassesId(int id);
}

<?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">
<!-- namespace:传入接口文件 -->  
<mapper namespace="com.pb.mapper.ClassesMapper">
   <resultMap type="Classes" id="ClassesResultMapper">
        <id column="class_id" property="id"/>
        <result column="class_name" property="name"/>
        <!-- 
        property="students"名字
        javaType="ArrayList"类型
        column="class_id"相对应外键的列
         -->

使用collection标签运用集合

        <collection property="student" javaType="ArrayList" column="class_id" select="findStudentsByClass"></collection>
   </resultMap>
   
   <resultMap type="Student" id="StudentResultMapper">
        <id column="id" property="id"/>
        <result column="stuname" property="name"/>
        <result column="age" property="age"/>
        <result column="brithday" property="bd"/>
   </resultMap>
   
   <select id="findByClassesId" parameterType="int" resultMap="ClassesResultMapper">
        select * from class where class_id=#{id}
   </select>
   
   <select id="findStudentsByClass" parameterType="int" resultMap="StudentResultMapper">
        select * from Student where class_id=#{id}
   </select>
</mapper>

测试类测试代码

        Classes cs=session.getMapper(ClassesMapper.class).findByClassesId(1);
           System.out.println(cs.getId()+"\t"+cs.getName());
           for(Student student:cs.getStudent()) {
        	   System.out.println(student.getId()+"\t"+student.getName());
           }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值