编程语言
首页 > 编程语言> > [mybatis]快速搭建一个mybatis程序,实现对数据的增删改查

[mybatis]快速搭建一个mybatis程序,实现对数据的增删改查

作者:互联网

什么是 MyBatis?

持久层

为什么需要mybatis

一个mybatis程序

1.创建一个数据库

2.在maven项目的pom.xml文件中导入依赖文件

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.29</version>
    </dependency>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.13.1</version>
    </dependency>

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.9</version>
</dependency>

3.在资源文件夹下命名一个mybatis_config.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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/jdbc?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123123"/>
            </dataSource>
        </environment>
    </environments>
    
</configuration>

4.编写操作数据库要用的SQLSession对象并且封装成一个工具类

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 java.io.IOException;
import java.io.InputStream;

/**
 * @author panglili
 * @create 2022-07-21-14:49
 */
public class MybatisUtil {
    static SqlSessionFactory build;
    static {
        String resource="mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);

            build = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //通过sqlSessionFactoryBuild创建拿到了工厂,由这个工厂就可以拿到sqlSession了
    //sqlSession中封装了所有操作数据库的代码
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = build.openSession();

        return sqlSession;
    }
}

5.与数据库对应的实体类

package pojo;

import java.util.Date;

/**
 * @author panglili
 * @create 2022-07-21-15:01
 */
public class perple {
    private int id;
    private String name;
    private int age;
    private Date birth;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

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

6.接口与接口的配置操作数据库文件,尽量命名为相同

package mapper;

import pojo.perple;

import java.util.List;

/**
 * @author panglili
 * @create 2022-07-21-15:07
 */
public interface perpleMapper {

    //查询所有信息
    List<perple> perples();

    //通过id查询某个用户
    perple queryById();
}
<?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="mapper.perpleMapper">

    <select id="perples" resultType="pojo.perples">
        select * from perple;
    </select>
</mapper>

7.注册到mybatis配置文件

<mappers>
        <mapper resource="mapper/perpleMapper.xml"></mapper>
    </mappers>

8.测试

package mapper;
import org.apache.ibatis.session.SqlSession;
import pojo.perple;
import util.MybatisUtil;
import java.util.List;
/**
 * @author panglili
 * @create 2022-07-21-15:16
 */
public class perpleTest {
    public void test(){
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        perpleMapper mapper = sqlSession.getMapper(perpleMapper.class);
        List<perple> perples = mapper.();
        for(int i=0;i<perples.size();i++){
            System.out.println(perples.get(i));
        }

    }
}

最后可能会遇到静态资源过滤的问题需要在pom配置文件加上处理

 <build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
            <filtering>true</filtering>
        </resource>
    </resources>
</build>

完整的增删改查

package mapper;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import pojo.perple;
import util.MybatisUtil;

import javax.print.attribute.standard.DateTimeAtCompleted;
import java.util.Date;
import java.util.List;

/**
 * @author panglili
 * @create 2022-07-21-15:16
 */
public class perpleTest {
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    perpleMapper mapper = sqlSession.getMapper(perpleMapper.class);

    @Test
    public void test(){
         List<perple> perples = mapper.queryAll();
        for(int i=0;i<perples.size();i++){
            System.out.println(perples.get(i));
        }
    }
    //通过id查询
    @Test
    public void test1(){
        perple perple = mapper.queryById(1);
        System.out.println(perple);
    }

    //删除
    @Test
    public void test2(){
        mapper.deleteById(1);
        sqlSession.commit();
    }

    //增加
    @Test
    public void test3(){

        perple perple=new perple(2,"tata",13,"2002-1");
        mapper.add(perple);
        //大坑 一定要开启提交事务
        sqlSession.commit();
    }


    //修改
    @Test
    public void test4(){
        perple perple=new perple(2,"tata",18,"2002-1");
        mapper.update(perple);
        sqlSession.commit();
    }
}

一定要记得开启事务!!!

标签:java,改查,增删,org,mybatis,import,apache,public
来源: https://www.cnblogs.com/lumanmanqixiuyuanxi/p/16512525.html