美文网首页
(四)MyBatis 采用注解方式实现CRUD

(四)MyBatis 采用注解方式实现CRUD

作者: 花季浅忆 | 来源:发表于2019-03-06 16:38 被阅读0次

采用注解方式相对于xml配置的方式就简单多了,那么她和xml配置的方式有什么区别呢。一般一些简单的CURD操作可以选择注解方式来实现,复杂的包括一对多,多对一,调用存储过程的都考虑采用xml配置的方式。

先看一下整个工程的目录结构

001.png

建表语句:

 create table users(  
    id int primary key auto_increment,  
    name varchar(255),
    age int
); 

1.首先使用IDEA建一个Maven工程。然后再pom.xml添加如下依赖

 <dependencies>
      <!-- mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.8</version>
        </dependency>


        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!-- junit测试包 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

2.mybatis.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="db.properties"/>-->
    <!-- 环境配置 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!-- 数据库连接相关配置 ,这里动态获取config.properties文件中的内容-->
            <dataSource type="POOLED">
            <property name="driver" value="com.mysql.jdbc.Driver" />
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false" />
            <property name="username" value="root" />
            <property name="password" value="wscjwacs" />
            </dataSource>
       
        </environment>
    </environments>
    <!-- mapping文件路径配置 -->
    <!--<mappers>-->
        <!--<mapper resource="mapper/userMapper.xml"/>-->
    <!--</mappers>-->
    <!-- 在配置文件中 关联包下的 接口类-->
    <mappers>
        <mapper class="com.flyz.UserMapper"/>
    </mappers>
</configuration>

3.UserMapper.java

package com.flyz;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;


public interface UserMapper {

    /*
     * 这是基于注解的映射方式,实现对数据的增删改查,将sql语句直接写在注解的括号中
     * 这是一个接口,其不需要类去实现它
     * 下边分别是插入,删除,修改,查询一个记录,查询所有的记录
     * */

    @Insert("insert into users(name,age) values(#{name},#{age})")
    public void insertT(User user);

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

    @Update("update users set name=#{name},age=#{age} where id=#{id}")
    public void updateT(User user);

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

    @Select("select * from users")
    public List<User> getAllUsers();
}
  1. User.java
package com.flyz;


public class User {
    // 实体类参数最好用包装类型
    private Integer id;
    private String name;
    private Integer age;

    public User(Integer id, String name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

5.MybatisUtils.java

package com.flyz;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MybatisUtils {
    public static SqlSessionFactory getFactory(){
        String resource="mybatis.xml";

        //加载mybatis 的配置文件(它也加载关联的映射文件)
        InputStream is=MybatisUtils.class.getClassLoader().getResourceAsStream(resource);
        //构建sqlSession 的工厂
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
        return factory;
    }
}

以上是所所有的文件

下面是test测试文件

import com.flyz.MybatisUtils;
import com.flyz.User;
import com.flyz.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;

import java.util.List;

public class UserTest {
    @Test
    //插入数据
    public void testInsert(){
        SqlSessionFactory factory= MybatisUtils.getFactory();
        SqlSession session=factory.openSession(true);
        //使用反射的方法
        UserMapper mapper=session.getMapper(UserMapper.class);
        mapper.insertT(new User(-1, "p", 4));
        mapper.insertT(new User(-1, "Jerry", 20));

        session.close();
    }

    @Test
    //删除数据
    public void testDelete(){
        SqlSessionFactory factory=MybatisUtils.getFactory();
        SqlSession session=factory.openSession(true);
        UserMapper mapper=session.getMapper(UserMapper.class);
        mapper.deleteById(1);
        session.close();
    }

    @Test
    //修改数据
    public void testUpdate(){
        SqlSessionFactory factory=MybatisUtils.getFactory();
        SqlSession session=factory.openSession(true);
        UserMapper mapper=session.getMapper(UserMapper.class);
        mapper.updateT(new User(2, "jjjjj", 232));
        session.close();
    }

    @Test
    //获取一条数据
    public void testGetUser(){
        SqlSessionFactory factory=MybatisUtils.getFactory();
        SqlSession session=factory.openSession(true);
        UserMapper mapper=session.getMapper(UserMapper.class);
        User user=mapper.getUser(2);
        session.close();
        System.out.println(user);
    }

    @Test
    //获取所有数据
    public void testGetAllUsers(){
        SqlSessionFactory factory=MybatisUtils.getFactory();
        SqlSession session=factory.openSession(true);
        UserMapper mapper=session.getMapper(UserMapper.class);
        List<User> users=mapper.getAllUsers();

        session.close();
        System.out.println(users);
    }
}

代码:https://download.csdn.net/download/wzgbgz/11002785

相关文章

网友评论

      本文标题:(四)MyBatis 采用注解方式实现CRUD

      本文链接:https://www.haomeiwen.com/subject/mshxpqtx.html