Mybatis使用步骤

一:导包

  

二、配置相关的xml文件 -- 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>
<!--加载数据库的配置文件,jdbc.properties文件是在项目的resources文件夹下-->
<properties resource="jdbc.properties"></properties>

<!--取别名,type属性的值是类的权限定名-->
<typeAliases>
<typeAlias type="cn.itsource.domain.Employee" alias="employee"></typeAlias>
<typeAlias type="cn.itsource.query.EmployeeQuery" alias="employeeQuery"></typeAlias>
</typeAliases>
<!--配置数据库的信息-->
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
<property name="url" value="${url}"/>
<property name="driver" value="${driverClassName}"/>
</dataSource>
</environment>
</environments>
  <!--domain类对应的xml-->
<mappers>
<mapper resource="cn/itsource/mapper/EmployeeMapper.xml"></mapper>
</mappers>
</configuration>

 三、 domain层建表

    public class Employee {

      private Long id;
      private String username;
      private String password;
      private Integer sex;
      private Integer age;
        此处省略set/get方法
    }

 四、准备mapper层(相当于以前的dao层)

  注意:方法名必须和EmployeeMapper.xml文件中配置的方法名必须一致

  public interface EmployeeMapper {
    //查询所有
    List<Employee> findAll();

    //高级查询
    List<Employee> findByQuery(EmployeeQuery query);


    //添加一个
    void save(Employee employee);


    //批量添加-使用数组方式
    void batchSaveByArray(Employee[] array);


    //批量添加-使用集合的方式
    void batchSaveByList(List<Employee> list);
  }

五、涉及到高级查询,就先准备一个高级查询的类,query层建一个EmployeeQuery高级查询类

  

  public class EmployeeQuery {
    private String username;//用户名
    private Integer sex;//性别
    private Integer minAge;//最小年龄
    private Integer maxAge;//最大年龄

      省略set/get方法

  }

 

六、配置EmployeeMapper.xml文件(文件暂时放在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">


  <mapper namespace="cn.itsource.mapper.EmployeeMapper">

   <!--

    抽取公共的SQL语句,每次写字段的时候都比较麻烦,所以就直接抽取出来了,用<sql>标签抽取,id名字任意取

    取值的时候用</include>标签取值

    -->
    <sql id="colum">
      (username,password,sex,age)
    </sql>
    <sql id="parme">
      (#{username},#{password},#{sex},#{age})
    </sql>
    <!--  查询方法用<select>,新增用<insert>,修改用<update> -->
    <!--查询所有:

      id属性对应的值,必须和EmployeeMapper接口中的方法名一致,

       resultType:返回值类型,要将查询结果封装到Employee这个类中,再装入集合里面返回,我这里使用的是别名,因为在mybatis-config.xml文件中配置了别名,

      不涉及到参数,所以这里就没有添加参数类型

    -->
    <select id="findAll"  resultType="employee">
      select * from  w_employee;
    </select>



    <!--高级查询:

      parameterType:参数类型,高级查询专门准备了一个查询的条件的类

      <if test="判断条件"> 满足条件要执行的内容,这里就只是拼接SQL语句</if> :xml的条件标签,

      <where>标签:会把标签里面的条件的第一个and 改成where,所以<if>标签里面满足条件的SQL语句都使用and连接

      注意:在xml中<(小于符号是一个特殊符号),默认是标签开始符,但是这里要判断年龄小于等于最大年龄,有2中解决方式,第一种忘记了,

      就记得第二种使用<![CDATA [ 这里的内容不会被xml解析 ] ]>

    -->
    <select id="findByQuery" parameterType="employeeQuery" resultType="employee">
      select * from w_employee
      <where>
        <if test="username!=null and username!=''" >
          and username like concat("%",#{username},"%")
        </if>
        <if test="minAge!=null">
          and age>=#{minAge}
        </if>
        <if test="maxAge!=null">
          and <![CDATA[age<=#{maxAge}]]>
        </if>
      </where>
    </select>

    <!--单个保存:

      useGeneratedKeys="true" keyColumn="id" keyProperty="id"

      以上配置是在一个方法里面做保存的时候,就可以拿到刚保存的数据的id,以前是必须要方法完成并保存到数据库才能获取到id,

      在做关系保存是有用,一个方法里同时保存一方和多方,先保存一方,获取到一方的id,再保存多方。

    -->
    <insert id="save" useGeneratedKeys="true" keyColumn="id" keyProperty="id"  parameterType="employee">
      insert into w_employee <include refid="colum"></include>
      values <include refid="parme"></include>
    </insert>

    <!--

      <include refid="colum"/>:引用<sql>标签中的数据,

      <foreach.> 循环标签, collection:指定类型进行循环,一般是数组和集合, 数组:参数类型就需要使用Object[]或者Object----parameterType="Object";

            集合:参数类型就是list(小写)

转载于:https://www.cnblogs.com/tuxiaoer/p/11217469.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 MyBatis步骤如下: 1. 引入 MyBatis 的依赖包 在 Maven 项目中,需要在 pom.xml 文件中引入 MyBatis 的依赖包,例如: ```xml <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.7</version> </dependency> ``` 2. 配置数据库连接信息 在 MyBatis 的配置文件中,需要配置数据库连接信息,包括数据库的 URL、用户名、密码等。例如,使用 MySQL 数据库的配置如下: ```xml <configuration> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="com.mysql.cj.jdbc.Driver"/> <property name="url" value="jdbc:mysql://localhost:3306/mybatis_test?serverTimezone=UTC&useSSL=false&allowPublicKeyRetrieval=true"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> </configuration> ``` 其中,`driver` 属性指定了数据库驱动类,`url` 属性指定了数据库的 URL,`username` 和 `password` 属性指定了数据库的用户名和密码。 3. 创建实体类 创建实体类,与数据库表对应。例如: ```java public class User { private Long id; private String username; private String password; // getter 和 setter 方法 } ``` 4. 创建 DAO 接口 创建 DAO 接口,定义需要执行的 SQL 语句。例如: ```java public interface UserMapper { List<User> selectUsers(); User selectUserById(Long id); void insertUser(User user); void updateUser(User user); void deleteUser(Long id); } ``` 5. 创建映射文件或者注解实现 使用映射文件或者注解实现 DAO 接口中的方法。例如,使用映射文件实现 `selectUsers` 方法如下: ```xml <!-- UserMapper.xml --> <mapper namespace="com.example.dao.UserMapper"> <select id="selectUsers" resultType="com.example.entity.User"> select * from user </select> </mapper> ``` 如果使用注解实现,可以在 DAO 接口中使用注解来定义 SQL 语句。例如: ```java public interface UserMapper { @Select("select * from user") List<User> selectUsers(); } ``` 6. 创建 MyBatis 的配置文件 创建 MyBatis 的配置文件,指定映射文件或者注解接口的位置。例如: ```xml <configuration> <mappers> <mapper resource="com/example/dao/UserMapper.xml"/> <mapper class="com.example.dao.OrderMapper"/> </mappers> </configuration> ``` 其中,`<mapper>` 标签可以指定映射文件或者注解接口的位置。 7. 创建 SqlSessionFactory 对象 通过配置文件创建 SqlSessionFactory 对象,例如: ```java String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); ``` 8. 创建 SqlSession 对象 通过 SqlSessionFactory 对象创建 SqlSession 对象,例如: ```java SqlSession sqlSession = sqlSessionFactory.openSession(); ``` 9. 调用 DAO 接口方法,执行 SQL 语句 通过 SqlSession 对象调用 DAO 接口方法,执行 SQL 语句,例如: ```java UserMapper userMapper = sqlSession.getMapper(UserMapper.class); List<User> users = userMapper.selectUsers(); ``` 10. 关闭 SqlSession 对象 执行完 SQL 语句后,需要关闭 SqlSession 对象,例如: ```java sqlSession.close(); ``` 以上就是使用 MyBatis步骤。具体的实现可以参考 MyBatis 的官方文档或者一些 MyBatis 的教程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值