MyBatis使用小结

Mybatis总结

花了一个小时列举了常见的Mybatis使用场景
1.一对一的场景
2. 一对多的场景
 3.多对多的场景
 
在使用之前,通常在项目中做一些提前准备。
a.往项目中导入jar包
     导入mybatis框架必须要用到的jar包 mybatis-3.3.0.jar和 ojdbc14.jar
但根据项目需要,有时会导入其他包,比如log4j-1.2.17.jar这个包可以用来生成日志
有时会导入junit-4.7.jar,这个jar包主要为项目提供单元测试。
b.在项目的src目录下创建文件mybatis-config.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 >
                < properties resource = "oracle.properties" >
                 <!-- 注意:是applications.properties文件中的值优先级高 -->
                </ properties >
                < typeAliases >
                    < typeAlias alias = "Book" type = "com.lm.bean.Book" />
                </ typeAliases >
                < environments default = "development" >
                    < environment id = "development" >
                     < transactionManager type = "JDBC" />
                      < dataSource type = "POOLED" >
                         <!-- 当数据库类型为mysql时使用下面的属性
                        <property name="driver" value="com.mysql.jdbc.Driver" />
                        <property name=" url " value="jdbc:mysql:// localhost :3306/test" />
                        -->
                         < property name = "driver" value = "${driver}" />
                         < property name = "url" value = "${url}" />
                         < property name = "username" value = "${username}" />
                         < property name = "password" value = "${password}" />
                     </ dataSource >
                    </ environment >
                </ environments >
                < mappers >
                    < mapper resource = "com/lm/mapper/BookMapper.xml" />
                </ mappers >
               </ configuration >

  如果项目中导入了 log4j-1.2.17.jar包,会在src目录下配置相关的log4j.properties文件
  log4j.properties文件的内容
   log4j.rootLogger= DEBUG, stdout
  log4j.appender.stdout = org.apache.log4j.ConsoleAppender
  log4j.appender.stdout.layout= org.apache.log4j.PatternLayout
  log4j.appender.stdout.layout.ConversionPattern= %d [%-5p] %c - %m%n
  #show sql
  log4j.logger.java.sql.ResultSet= INFO  
   log4j.logger.org .apache= INFO  
  log4j.logger.java.sql.Connection= DEBUG  
  log4j.logger.java.sql.Statement= DEBUG  
  log4j.logger.java.sql.PreparedStatement= DEBUG
  有时候连接数据库的时候也会创建oracle.properties文件,这是为了项目以后更换了数据
库之后(如oracle更换成mysql数据库)不用修改 mybatis-config.xml文件。
   oracle.properties文件的内容
         driver=oracle.jdbc.driver.OracleDriver
     url=jdbc:oracle:thin:@localhost:1521:XE  
     username=oracle
     password=oracle
  
   mysql.properties文件的内容
        driver=com.mysql.jdbc.Driver
     url=jdbc:mysql://localhost:3306/test
      username=oracle
     password=oracle

  所有准备工作做完之后开始逐一解决需求
   
1.一对一场景(丈夫对妻子)
 首先写pojo类

    class Wife implements Serializable{
 
public class Wife implements Serializable{
      /**
      *
      */
      private static final long serialVersionUID = 1L;  //实现序列化接口是为了有时进行二次缓存会用到
   
      private Integer wifeId ;//这里使用Integer是为了避免int类型默认值为0的情况
      private String name ;
      private Integer age ;
        set/get 
        toString

    }
 丈夫类

public class Husband implements Serializable{
      /**
      *
      */
      private static final long serialVersionUID = 1L;
     
      private Integer husbandId ;
      private String name ;
      private Integer age ;
      private Wife wife ;
             set/get
       toString
     }
   
然后创建数据库
 create table wifes(
  wife_id number primary key,
  name varchar2(15) not null,
  age number
 );
 create table husbands(
 husband_id number primary key,
 name varchar2(15) not null,
 age number,
 wife_id number references wifes(wife_id)
 );
 先往数据库中插入几条数据方便测试
  insert into wifes values (1, 'xiaowen' ,25);
 insert into wifes values (2, 'xiaodie' ,25);
 insert into wifes values (3, 'xiaozhang' ,25);
 insert into husbands values (1, 'xiaomeng' ,23,1);
 insert into husbands values (2, 'xiaoli' ,23,3);
 insert into husbands values (3, 'xiaoyi' ,23,2);

接着写映射接口
public interface OtoMapper{
  public Husband findHusbandWithWifeById(int id);//通过id查询带有妻子信息的丈夫
  public void  insertHusband(Husband husband);
}
配置与接口相对应的配置文件
 <!-- 注意namespace的名字一定要和接口的全名完全对应 -->
<mapper namespace="OtoMapper"> 
 <!-- 注意类型一定要时所对应的类的全名 -->
    <resultMap id="WifeResult" type="Wife"> 
        <id property="wifeId" column="wife_id" />
         <result property="name" column="name" />
         <result property="age" column="age" />
    </resultMap>
 
   <resultMap id="HusbandResult" type="Husband">
        <id property="husbandId" column="husband_id" />
        <result property="name" column="name" />
        <result property="age" column="age" />
        <association property="wife" resultMap=" WifeResult " />
   </resultMap> 

  < insert id = "insertWife" parameterType = "Wife" >
               < selectKey keyProperty = "wifeId" resultType = "int" order = "BEFORE" >
                 select my_seq.nextval from dual
               </ selectKey >
               insert into wifes
               values(#{wifeId},#{name},#{age})
   </ insert >
   < insert id = "insertHusband" parameterType = "Husband" >
               < selectKey keyProperty = "husbandId" resultType = "int" order = "BEFORE" >
                  select my_seq.nextval from dual
               </ selectKey >
      <!--注意插入丈夫的时候一定要妻子对象一定把妻子的id属性写出来-->
               insert into husbands
               values(#{husbandId},#{name},#{age},#{wife.wifeId})
    </ insert >
            <!-- 注意id一定要和接口中对应的方法名一致 -->
  <select id=" findHusbandWithWifeById " parameterType="int " resultMap=" WifeResult ">
          select * from husbands where husband_id=#{husbandId}
  </select>
<mapper>

然后写测试类,可以使用单元测试,也可以使用main()方法



2.一对多场景(小组对用户)
 第一步 写pojo类

public class User implements Serializable{
      /**
      *
      */
      private static final long serialVersionUID = 1L;
     
      private Integer userId ;
      private String userName ;
     
      private Group group ; //这里维护group对象,是为了将来通过查询user可以显示出在哪个小组中
       
        set/get
        toString
}
小组类
public class Group implements Serializable{
      /**
      *
      */
      private static final long serialVersionUID = 1L;
  
      private Integer groupId ;
      private String groupName ;
       private List<User> users ; //查询用户同时显示用户的信息,通常都是在少的一方list多的一方
  
        set/get
        toString
}

2.建数据库表

create table t_group(
group_id number primary key,
groupName varchar2(15) not null
);
create table t_user(
t_user_id number primary key,
userName varchar2(15),
group_id number references t_group(group_id)   //一对多的时候通常都是多的一方维护少的一方
);

先往数据库中插入几条数据方便测试
insert into t_group values (1, 'Lol' );
insert into t_group values (2, 'JueDi' );
insert into t_user values (1, 'zhangsan' ,1);
insert into t_user values (2, 'lucy' ,2);
insert into t_user values (3, 'tom' ,1);
insert into t_user values (4, 'xiaohua' ,2);
insert into t_user values (5, 'xiaowen' ,1);

3.写映射接口
public interface OtmMapper{
  public Group findGroupById(int id);
  public User findUserById(int id);
}
4.写和接口相关的配置文件
  <mapper namespace=" OtmMapper ">
    <resultMap id="UserResult" type="User">
           <id property="userId" column="t_user_id" />
           <result property="userName" column="userName">
    </resultMap>

   <resultMap id="GroupResult" type="Group">
        <id property="groupId" column="group_id" />
       <result proeprty="groupName" column="groupName" />
         <!--下面的collection可以理解为多个对象组成的集合,正好和pojo类中的list集合对应。这样就能记住-->
       <collection pproperty="users" resultMap=" UserResult "> 
 
   </resultMap>
   <!--以上的配置文件就可以完成查询所需小组,并且小组中包含多个用户信息-->
   <select id=" findGroupById " parameter="int" resultMap=" GroupResult ">
         select * from 
        t_group g,t_user u
        where u.group_id=g.group_id
        and g.group_id=#{groupId}
   </select>
   
 <!--注意查询用户的时候,因为用户拥护了小组,也就是说users数据库表中的group外键也要房放进去  以 group.groupId的形式交给Mybatis处理后放入数据库中的user表中形成外键-->
   < insert id = "insertUser" parameterType = "User" >
              < selectKey keyProperty = "userId" resultType = "int" order = "BEFORE" >
                   select my_seq.nextval from dual
              </ selectKey >
              insert into t_user
              values(#{userId},#{userName},#{group.groupId})
   </ insert >
   
  <!--高能,如果想查询带有小组的信息的用户时,需要下面的配置文件-->
     <resultMap id="UserResltandGroupResult" parameterType="int"  extends=" UserResult "   >
      <association property="group" resulMap=" GroupResult " />      
 </resultMap>

   <select  id=" findUserWithGroupById " parameterType="int"    resultMap=" UserResltandGroupResult ">
    select * from t_user where t_user_id=#{userId}
  </select>

</mapper>
  




3.多对多场景(学生对课程)

 < resultMap id="帅哥们Result" type="帅哥类">
<id property="帅哥id" cloumn="帅哥id">
<result property="gender" cloumn="gender">
</resultMap>
<resultMap id="美女们Result" type="美女类">
<id property="美女id" cloumn="美女id">
<result property="gender" cloumn="gender">
</resultMap>
       // 通过帅哥找美女是这样写的
<resultMap id="帅哥们和美女们Result" type="帅哥类" extends="帅哥们Result"> //背会第一句
<id property="帅哥id" cloumn="帅哥id">
<result property="gender" cloumn="gender">
<collection property="美女们" resultMap="美女们Result"> //背会
</resultMap>
select * from 帅哥和美女们, 帅哥们,美女们
  where 帅哥id=#{帅哥id}
    and  帅哥们id=sc.student_id
    and 美女们id=sc.course_id

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值