mybatis-基于anno的crud

Posted 拾亿~

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis-基于anno的crud相关的知识,希望对你有一定的参考价值。

创建maven工程

mybatis-anno/
	|-src/
	|		|-main/
	|		|		|-java/
	|		|		|-resources/		
	|		|-test/
	|-pom.xml
  • mybatis-anno/:项目目录
  • mybatis-anno/src/:java类路径
  • mybatis-anno/src/main/:此处就是java代码,如pojo,mapper
  • mybatis-anno/src/resources/:此处存放mybatis-config.xml(mybatis主配置文件)和(jdbcConfig.properties数据库连接文件)...
  • mybatis-anno/src/test/:测试

添加依赖

在pom.xml文件中,添加需要的依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>mybatis-anno</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>9</maven.compiler.source>
        <maven.compiler.target>9</maven.compiler.target>
    </properties>

    <dependencies>
<!--    mybatis 核心依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.7</version>
        </dependency>
<!--		mysql8驱动依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
        </dependency>
<!--		junit4测试依赖-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

创建pojo类

在main/java/中创建com/mybatis_anno/pojo/User类

main/java/com/mybatis_anno/pojo/User.class
package com.mybatis_anno.pojo;

public class User implements Serializable{//对应user表
    private Integer uid; //对应uid
    private String uname;//对应uname
    private String usex;//对应usex
    private Integer uage;//对应uage

    public User() {
    }

    public User(Integer uid, String uname, String usex, Integer uage) {
        this.uid = uid;
        this.uname = uname;
        this.usex = usex;
        this.uage = uage;
    }

    public Integer getUid() {
        return uid;
    }

    public void setUid(Integer uid) {
        this.uid = uid;
    }

    public String getUname() {
        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

    public String getUsex() {
        return usex;
    }

    public void setUsex(String usex) {
        this.usex = usex;
    }

    public Integer getUage() {
        return uage;
    }

    public void setUage(Integer uage) {
        this.uage = uage;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", uname=\'" + uname + \'\\\'\' +
                ", usex=\'" + usex + \'\\\'\' +
                ", uage=" + uage +
                \'}\';
    }
}

创建mapper接口

在main/java/中创建com/mybatis_anno/mapper/IUserMapper接口

main/java/com/mybatis_anno/mapper/IUserMapper.class
package com.mybatis_anno.mapper;

import com.mybatis_anno.pojo.User;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface IUserMapper {
    @Select("select * from user")
    List<User> findUserAll();

    @Select("select * from user where uid=#{uid}")
    User findUserById(Integer userId);

    @Select("select * from user where uname like #{uname}")
    List<User> findUserByName(String userName);

    @Insert("insert into user(uname,usex,uage) value(#{uname},#{usex},#{uage})")
    int saveUser(User user);

    @Update("update user set uname=#{uname},usex=#{usex},uage=#{uage} where uid=#{uid}")
    int updateUser(User user);

    @Delete("delete from user where uid=#{uid}")
    int deleteUser(Integer userId);

    @Select("select count(*) from user")
    int findUserAllTotal();
}

创建主配置文件

在resources中创建mybatis-config.xml和jdbcConfig.properties

resources/mybatis-config.xml
resources/jdbcConfig.properties
<?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="jdbcConfig.properties"></properties>
<!--    配置别名-->
    <typeAliases>
        <package name="com.mybatis_anno.pojo"/>
    </typeAliases>
<!--    配置环境-->
    <environments default="mysql">
        <environment id="mysql">
            <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>
        <package name="com.mybatis_anno.mapper"/>
    </mappers>
</configuration>
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
jdbc.username=root
jdbc.password=root

创建测试类

在test/java中创建TestDemo.class

test/java/TestDemo.class
import com.mybatis_anno.mapper.IUserMapper;
import com.mybatis_anno.pojo.User;
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.After;
import org.junit.Before;
import org.junit.Test;

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

public class TestDemo {
    private InputStream is;
    private SqlSessionFactory sqlSessionFactory;
    private SqlSession session;
    private IUserMapper userMapper;

    @Before
    public void init() throws IOException {
        String resource = "mybatis-config.xml";
        is = Resources.getResourceAsStream(resource);
        session = new SqlSessionFactoryBuilder().build(is).openSession();
        userMapper = session.getMapper(IUserMapper.class);
    }
    @After
    public void destory() throws IOException {
        session.commit();
        session.close();
        is.close();
    }

    @Test
    public void testFindUserAll(){
        List<User> users = userMapper.findUserAll();
        System.out.println(users);
    }

    @Test
    public void testFindUserById(){
        User user = userMapper.findUserById(14);
        System.out.println(user);
    }

    @Test
    public void testFindUserByName(){
        List<User> users = userMapper.findUserByName("%a%");
        System.out.println(users);
    }

    @Test
    public void testSaveUser(){
        User user = new User();
        user.setUname("afaf");
        user.setUsex("afa");
        user.setUage(24);
        userMapper.saveUser(user);
    }

    @Test
    public void testUpdateUser(){
        User user = new User();
        user.setUid(14);
        user.setUname("akfka");
        user.setUsex("sf");
        user.setUage(141);
        userMapper.updateUser(user);
    }

    @Test
    public void testDelUser(){
        userMapper.deleteUser(12);
    }

    @Test
    public void testFindUserAllTotal(){
        int total = userMapper.findUserAllTotal();
        System.out.println(total);
    }
}

以上是关于mybatis-基于anno的crud的主要内容,如果未能解决你的问题,请参考以下文章

基于SSM之Mybatis接口实现增删改查(CRUD)功能

基于mybatis的crud demo

MyBatis01基于配置的CRUD操作

基于MyBatis的CRUD操作

MyBatis系列:基于MyBatisUtils工具类完成CRUD操作

基于springBoot,,springCloud,mybatis 框架简单 微服开发 ==CRUD