IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 开发工具 -> MyBatis注解开发 -> 正文阅读

[开发工具]MyBatis注解开发

1、常用注解

@Insert:新增

@Update:更新

@Delete:删除

@Select:查询

@Result:结果集封装

@Results:可以与@Result 一起使用,封装多个结果集

@One:一对一结果集封装

@Many:一对多结果集封装

2、简单的增删改查

(1)创建项目

?(2)配置pom.xml文件

<dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.45</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

(3)编写实体类和数据库

public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;}

(4)配置核心文件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>

    <!--通过properties标签加载外部properties文件-->
    <properties resource="jdbc.properties"></properties>

    <!--数据源环境-->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--加载映射文件   使用注解前-->
    <!--<mappers>
        <mapper resource="com/dhh/mapper/UserMapper.xml"/>
    </mappers>-->

    <!--加载配置关系  使用注解后 TODO-->
    <mappers>
        <!--指定接口所在的包 -->
        <package name="com.dhh.mapper"/>
    </mappers>


</configuration>

(5)配置UserMapper.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="com.dhh.mapper.UserMapper"><!--调用名称 userMapper.findAll-->

    <insert id="save" parameterType="user">
        insert into user values(#{id},#{username},#{password},#{birthday})
    </insert>

     <delete id="delete" parameterType="int">
        delete from user where id=#{id}
    </delete>

    <update id="update" parameterType="user">
        update user set username=#{username},password=#{password} where id=#{id}
    </update>

    <select id="findAll" resultType="user">
        select * from user
    </select>

    <select id="findById" parameterType="int" resultMap="user">
        select * from user where id=#{id}
    </select>


</mapper>

使用注解:直接在UserMapper接口中写入SQL语句

package com.dhh.mapper;

import com.dhh.domain.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

public interface UserMapper {
    @Insert("insert into user values(#{id},#{username},#{password},#{birthday})")
    public void save(User user);

    @Update("update user set username=#{username},password=#{password} where id=#{id}")
    public void update(User user);

    @Delete("delete from user where id=#{id}")
    public void delete(int id);

    @Select("select * from user where id=#{id}")
    public User findById(int id);

    @Select("select * from user")
    public List<User> findAll();

}

(6)编写测试类

package com.dhh.test;

import com.dhh.domain.User;
import com.dhh.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisTest {
    private UserMapper mapper;

    @Before    //代码抽取
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void testSave(){
        User user =new User();
        user.setUsername("sisi");
        user.setPassword("111");
        mapper.save(user);
    }

    @Test
    public void testUpdate(){
        User user =new User();
        user.setId(5);
        user.setUsername("sisi");
        user.setPassword("123");
        mapper.update(user);
    }

    @Test
    public void testDelete(){
        User user =new User();
        mapper.delete(17);
    }

    @Test
    public void testFindById(){
       User user= mapper.findById(4);
        System.out.println(user);
    }

    @Test
    public void testFindAll(){
        List<User> all= mapper.findAll();
        for (User user:all) {
            System.out.println(user);
        }
    }
}

3、MyBatis的注解实现复杂映射开发

我们可以使用@Result注解、@Results注解、@One注解、@Many注解组合完成复杂关系配置

3.1 一对一?

(1)编写实体类和数据库

public class Order {
    private int id;
    private Date ordertime;  //下单时间
    private double total;   //总金额
    private User user;   //当前订单属于哪一个用户
}

?(2)使用注解:直接在OrderMapper.xml接口中写入SQL语句

package com.dhh.mapper;

import com.dhh.domain.Order;
import com.dhh.domain.User;
import org.apache.ibatis.annotations.One;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface OrderMapper {

    @Select("select * from orders where uid=#{uid}")
    public List<Order> findByUid(int uid);

    /*  一对一查询方式一
    @Select("select *,o.id oid from orders o,user u where o.uid=u.id")
    @Results({
            @Result(column = "oid",property = "id"),
            @Result(column = "ordertime",property = "ordertime"),
            @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();
    */

    //一对一查询方式二
    @Select("select * from orders")
    @Results({
            @Result(column = "oid",property = "id"),
            @Result(column = "ordertime",property = "ordertime"),
            @Result(column = "total",property = "total"),
            @Result(
                    property = "user",//要封装的属性名称
                    column = "uid",//根据哪个字段去查询user表的数据
                    javaType = User.class,//要封装的实体类型
                    //select属性,代表查询的哪个接口的方法获得数据
                    one=@One(select = "com.dhh.mapper.UserMapper.findById")
            )
    })
    public List<Order> findAll();


}

(3)测试代码

package com.dhh.test;

import com.dhh.domain.Order;
import com.dhh.domain.User;
import com.dhh.mapper.OrderMapper;
import com.dhh.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisTest2 {
    private OrderMapper mapper;

    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(OrderMapper.class);
    }

    @Test
    public void testSave(){

        List<Order> all = mapper.findAll();
        for(Order order : all){
            System.out.println(all);
        }
    }


}

3.2 一对多

(1)创建实体类

public class User {
    private int id;
    private String username;
    private String password;
    private Date birthday;

   //当前用户具有的订单
    private List<Order> orderList;
}

(2)在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.dhh.mapper.OrderMapper.findByUid")
            )
    })
    public List<User> findUserAndOrderAll();

使用OrderMapper接口中的方法(子查询)

(4)测试

package com.dhh.test;

import com.dhh.domain.Order;
import com.dhh.domain.User;
import com.dhh.mapper.OrderMapper;
import com.dhh.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisTest3 {
    private UserMapper mapper;

    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void testSave(){
        List<User> userAndOrderAll= mapper.findUserAndOrderAll();
        for (User user:userAndOrderAll) {
            System.out.println(user);
        }
    }
}

3.3 多对多

(1)创建实体类

public class Role {
    private int id;
    private String roleName;
    private String roleDesc;
}

在User实体类中追加属性:


    //当前用户具备哪些角色
    private List<Role> roleList;

(2)新建RoleMapper接口,编写role方法(子查询使用)


public interface RoleMapper {
    @Select("select * from sys_user_role ur,sys_role r 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(id = true,column = "username",property = "username"),
            @Result(id = true,column = "password",property = "password"),
            @Result(
                    property = "roleList",
                    column = "id",
                    javaType = List.class,
                    many = @Many(select = "com.dhh.mapper.RoleMapper.findByUid")
            )
    })
    public List<User> findUserAndRoleAll();

(4)测试

package com.dhh.test;

import com.dhh.domain.User;
import com.dhh.mapper.UserMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyBatisTest4 {
    private UserMapper mapper;
    //多对多
    @Before
    public void before() throws IOException {
        InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        mapper = sqlSession.getMapper(UserMapper.class);
    }

    @Test
    public void testSave(){
        List<User> userAndRoleAll= mapper.findUserAndRoleAll();
        for (User user:userAndRoleAll) {
            System.out.println(user);
        }
    }
}

总结:坚持很难,放弃容易,再接再厉,一起进步!

  开发工具 最新文章
Postman接口测试之Mock快速入门
ASCII码空格替换查表_最全ASCII码对照表0-2
如何使用 ssh 建立 socks 代理
Typora配合PicGo阿里云图床配置
SoapUI、Jmeter、Postman三种接口测试工具的
github用相对路径显示图片_GitHub 中 readm
Windows编译g2o及其g2o viewer
解决jupyter notebook无法连接/ jupyter连接
Git恢复到之前版本
VScode常用快捷键
上一篇文章      下一篇文章      查看所有文章
加:2022-04-26 11:58:27  更:2022-04-26 11:59:53 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/26 2:36:19-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码