• 17mybatis注解开发


    简单理解:

    • 使用mybatis注解开发,就不用再写UserMapper.xml配置文件,直接在接口中的方法上面用注解完成。

    • 实现简单增删改查,就用Select Delete Update Insert注解。

    • 实现复杂查询,就需要用到Results Result One Many注解,组合完成复杂关系的配置。

    简单注解:

    • @Select("select * from user")
    • @Delete("delete from user where id=#{id}")

    增删改查注解

    注解开发步骤:

    1. 实现数据表user(id, username, password)

    2. 导入坐标(mysql, mybatis)

    3. 在domain包中写User.java类

    4. 在dao包中实现UserMapper.java接口,定义方法,并用注解写sql语句

      public interface UserMapper {
      
          @Select("select * from user")
          public List<User> findAll();
      
          @Insert("insert into user values(#{id}, #{username}, #{password})")
          public void save(User user);
      
          @Update("update user set password=#{password} where id=#{id}")
          public void update(User user);
      
          @Delete("delete from user where id=#{id}")
          public void delete(int id);
      }
      
    5. 在sqlMapConfig.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>
      <!--自定义别名-->
          <typeAliases>
              <typeAlias type="com.domain.User" alias="user"/>
          </typeAliases>
      <!--数据源环境-->
          <environments default="developement">
              <environment id="developement">
                  <transactionManager type="JDBC"></transactionManager>
                  <dataSource type="POOLED">
                      <property name="driver" value="com.mysql.jdbc.Driver"/>
                      <property name="url" value="jdbc:mysql://localhost:3306/db1"/>
                      <property name="username" value="root"/>
                      <property name="password" value="root"/>
                  </dataSource>
              </environment>
          </environments>
      <!--加载映射文件-->
      <!--    <mappers>-->
      <!--        <mapper resource="UserMapper.xml"/>-->
      <!--    </mappers>-->
      <!--加载映射关系-->
          <mappers>
              <package name="com.dao"/>
          </mappers>
      </configuration>
      
    6. 测试(和原来一样)

      @Test
      public void test1() throws IOException {
          //  获取核心配置文件
          InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
          // 获取session工厂对象
          SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
          // 获得session会话对象
          SqlSession sqlSession = sqlSessionFactory.openSession();
          // 获得mapper
          UserMapper mapper = sqlSession.getMapper(UserMapper.class);
          // 执行
          List<User> all = mapper.findAll();
          for (User u : all) {
              System.out.println(u);
          }
          // 释放资源
          sqlSession.close();
      }
      

    1v1注解开发

    1v1注解开发:

    1. 编写User和Order类

    2. 编写OrderMapper接口,并定义方法,并用注解开发

      public interface OrderMapper {
          @Select("select *, o.id oid from orders o, user u where o.uid=u.id")
          @Results({
                  @Result(column = "oid", property = "id"),
                  @Result(column = "ordername", property = "ordername"),
                  @Result(column = "total", property = "total"),
                  @Result(column = "uid", property = "user.id"),
                  @Result(column = "username", property = "user.username"),
                  @Result(column = "password", property = "user.password")
          })
          public List<Order> findAll();
      }
      
    3. 测试

    1v1注解开发的另一种写法:(用这种的较多)

    • 首先UserMapper中需要注解开发findById方法

    • 再在OrderMapper中开发

      public interface OrderMapper {
          @Select("select * from orders")
          @Results({
                  @Result(column = "id", property = "id"),
                  @Result(column = "ordername", property = "ordername"),
                  @Result(column = "total", property = "total"),
                  @Result(
                          property = "user",
                          column = "uid",
                          javaType = User.class,
                          one = @One(select = "com.dao.UserMapper.findById")
                  )
          })
          public List<Order> findAll();
      }
      

    1vM注解开发

    1. 在User中添加成员变量private List<Order> orderList;

    2. 在OrderMapper中注解开发findByUid方法

    3. 在UserMapper中注解开发

      @Select("select * from user")
      @Results({
              @Result(id=true, column = "id", property = "id"),
              @Result(column = "username", property = "username"),
              @Result(column = "password", property = "password"),
              @Result(
                      property = "orderList",
                      column = "id",
                      javaType = List.class,
                      many = @Many(select = "com.dao.OrderMapper.findByUid")
              )
      })
      public List<User> findAllUserAndOrder();
      
    4. 测试

    MvM注解开发

    多对多关系需要引入一个中间表,所以有三个数据表:一个用户对应多个角色,一个角色对应多个用户

    user(id, username, password)
    user_role(user_id, role_id)
    role(id, rolename)
    

    多对多形式上和一对多差不多:

    1. 在User中定义成员变量private List<Role> roleList;

    2. 在RoleMapper中注解开发

      @Select("select * from role r, user_role ur where ur.roleId=r.id and ur.userId=uid")
      public List<Role> findByUid(int uid);
      
    3. 在UserMapper中注解开发

      @Select("select * from user")
      @Results({
              @Result(id = true, column = "id", property = "id"),
              @Result(column = "username", property = "username"),
              @Result(column = "password", property = "password"),
              @Result(
                      property = "roleList",
                      column = "id",
                      javaType = List.class,
                      many = @Many(select = "com.dao.RoleMapper.findByUid")
              )
      })
      public List<User> findAllUserAndRole();
      
    4. 测试

  • 相关阅读:
    django 定时任务 django-crontab 的使用
    Django中更新多个对象数据与删除对象的方法
    Django复制记录的方法
    Python中关于日期的计算总结
    django中添加日志功能
    Python 日期时间datetime 加一天,减一天,加减一小时一分钟,加减一年
    根据后端传的时间前端js进行倒计时
    输入pip命令报错:from pip import main ImportError: cannot import name 'main'
    操作uwsgi命令
    关于linux下安装mysqlclient报 Failed building wheel for mysqlclient问题
  • 原文地址:https://www.cnblogs.com/mingriyingying/p/13639628.html
Copyright © 2020-2023  润新知