Mybatis基于注解实现CRUD

Mybatis基于注解实现CRUD

1.准备一张表

create table t_teacher(
id int primary key auto_increment,
name varchar(20),
phone int,
ctime datetime
);

2.在pom.xml中导入项目所需要的jar包

    <dependencies>
        <!--        Mybatis的jar  -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.10</version>
        </dependency>
        <!--        Mysql驱动的jar-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.31</version>
        </dependency>
        <!--        Lombok 简化类的工具包-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <!--        单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13.1</version>
            <scope>test</scope>
        </dependency>
   </dependencies>

3.创建实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Teacher {
    private Integer id;
    private String name;
    private Integer phone;
    private Date ctime;

    public Teacher(String name, Integer phone, Date ctime) {
        this.name = name;
        this.phone = phone;
        this.ctime = ctime;
    }
}

4.编写mapper接口

public interface TeacherDao {
    @Select("select * from t_teacher")
    @ResultType(Teacher.class)
    List<Teacher> selectAll();
    @Insert("insert into t_teacher(name,phone,ctime)values(#{name},#{phone},now())")
    @Options(useGeneratedKeys = true,keyProperty = "id")
    int add(Teacher teacher);
    @Update("update t_teacher set name=#{name},phone=#{phone},ctime=#{ctime} where id=#{id}")
    int update(Teacher teacher);
    @Delete("delete from t_teacher where id=#{id}")
    int delectById(int id);
}

5.创建mybatis核心配置文件

<?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">
<!--Mybatis全局配置-->
<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/db_gp01"/>
                <property name="username" value="root"/>
                <property name="password" value="mjl7665379"/>
            </dataSource>
        </environment>

    </environments>

    <!--引入映射文件 注册-->
    <mappers>
        <!--        映射文件都需要注册,才会生效-->
       <mapper class="com.mjl.dao.TeacherDao"/>

    </mappers>
</configuration>

5.创建工具类

public  class MybatisUtil {
     public static  <T> T getMapper(Class<T> c) throws IOException {
         //创建会话工厂对象,加载配置文件
          SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsReader("mybatis.xml"));
          //创建会话对象
          SqlSession sqlSession = factory.openSession(true);
          return sqlSession.getMapper(c);
     }
}

6.测试

public class TestTeacher {
    @Test
    public  void selectAll() throws IOException {
        TeacherDao mapper = MybatisUtil.getMapper(TeacherDao.class);
        List<Teacher> teachers = mapper.selectAll();
        System.out.println(teachers);
    }

    @Test
    public void testAdd() throws IOException {
        TeacherDao mapper = MybatisUtil.getMapper(TeacherDao.class);
        Teacher teacher = new Teacher("王老师", 111, null);
        int i = mapper.add(teacher);
        System.out.println("添加:"+i);

    }
   @Test
   public void testDelectById() throws IOException {
       TeacherDao mapper = MybatisUtil.getMapper(TeacherDao.class);
       int i = mapper.delectById(3);
       System.out.println("删除:"+i);
   }
   @Test
    public void testUpdate() throws IOException {
       TeacherDao mapper = MybatisUtil.getMapper(TeacherDao.class);
       Teacher teacher = new Teacher();
       teacher.setName("张老师");
       teacher.setPhone(110);
       teacher.setCtime(null);
       teacher.setId(1);
       int i = mapper.update(teacher);
       System.out.println("修改:"+i);
   }
}

补充:

注解作用
1@Insert 修饰方法编写新增的SQL语句
2@Options 修饰方法,配合@Insert注解获取自增主键的值,useGeneratedKeys = true,keyProperty = “id”)
3@Delete 修饰方法编写删除的SQL语句
4@Update 修饰方法编写修改的SQL语句
5@Select 修饰方法编写查询的SQL语句
6@ResultType 修饰方法设置对应的类的字节码对象

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值