美文网首页
在IDEA中用MyBatis实现简单的增删改查

在IDEA中用MyBatis实现简单的增删改查

作者: 这样你就找不到我了 | 来源:发表于2020-12-08 13:49 被阅读0次
  • 在IDEA中新建maven项目

  • 文件目录

/src
  /main
    /java
      /com
        /dyl
          /dao
            /IUserDao.java
          /domain
            /User.java
    /resources
      /log4j.properties
      /sqlMapConfig.xml
  /test
    /java
      /MybatisTest.java
 /pom.xml
  • 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_demo</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <!--    mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>

        <!--日志 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        
        <!--测试 (直接运行函数)-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>
  • 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>
    <!--配置环境 -->
    <environments default="mysql">
<!--        配置mysql环境-->
        <environment id="mysql">
<!--            配置事物的类型-->
            <transactionManager type="JDBC"></transactionManager>
<!--            配置数据源(连接池)-->
            <dataSource type="POOLED">
                <!--                配置连接数据库的4个基本信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis_demo"/>
                <property name="username" value="root"/>
                <property name="password" value="1980897959"/>
            </dataSource>
        </environment>
    </environments>

    <!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件 -->
    <mappers>
        <mapper class="com.dyl.dao.IUserDao"/>
    </mappers>

</configuration>
  • log4j.properties.xml文件配置

# set root category priority ro INFO and its only appender to CONSOLE
# log4j.rootCategory=INFO,CONSOLE DEBUG info warn error fatal
log4j.rootCategory = DEBUG,CONSOLE,LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout

log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601}%-6r[%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout
log4j.appender.LOGFILE=org.apache.log4j.FileAppender

log4j.appender.LOGFILE.File=d:\\axis.log

log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601}%-6r[%15.15t] %-5p %30.30c %x - %m\n
  • IUserDao

package com.dyl.dao;

import com.dyl.domain.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 IUserDao {
    //查询所有操作
    @Select("select * from user")
    List<User> findAll();

    //保存操作
    @Insert("insert into user(username,password) values(#{username}, #{password})")
    void saveUser(User user);

    //更新操作
    @Update("update user set username=#{username},password=#{password} where username=#{username}")
    void updateUser(User user);

    //删除操作
    @Delete("delete from user where username=#{username}")
    void deleteUser(User user);

    //根据用户名模糊查询
    @Select("select * from user where username like #{username}")
    List<User> findByName(String username);
}

  • User

package com.dyl.domain;

import java.io.Serializable;

public class User implements Serializable {
    private String username;
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

  • MybatisTest

import com.dyl.dao.IUserDao;
import com.dyl.domain.User;
import org.apache.ibatis.annotations.Update;
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 javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MybatisTest {

    private InputStream in;
    private SqlSession session;
    private IUserDao userDao;

    @Before//用于在测试方法执行前执行
    public void init() throws IOException {
        in = Resources.getResourceAsStream("SqlMapConfig.xml");
        // 2,创建SqlSessionFactory工厂
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(in);
        //3,使用工厂生产SqlSession对象
        session = factory.openSession();
        //4.使用SqlSession创建Dao接口的代理对象
        userDao = session.getMapper(IUserDao.class);
    }

    @After//用于在测试方法执行后执行
    public void destroy() throws IOException {
        session.close();
        in.close();
    }

    @Test//查
    public void testFindAll() throws IOException {
        List<User> users = userDao.findAll();
        for(User user : users){
            System.out.println(user);
        }
    }
    @Test//保存
    public void testSave() throws IOException {
        User user = new User();
        user.setUsername("dyl");
        user.setPassword("12345678");
        //5. 使用代理对象执行方法
        userDao.saveUser(user);
        session.commit();
    }

    @Test//更新
    public void testUpdate(){
        User user = new User();
        user.setUsername("dyl");
        user.setPassword("12345678");
        userDao.updateUser(user);
        session.commit();
    }

    @Test//删除
    public void testDelete(){
        User user = new User();
        user.setUsername("dyl");
        userDao.deleteUser(user);
        session.commit();
    }

    @Test//模糊查找
    public void testFindByName(){
        String keyName = "%w%";
        List<User> user = userDao.findByName(keyName);
        System.out.println(user);
    }

}

对MybatisTest.java中的testFindAll()方法说一下我的理解:

@Test注解使得testFindAll()可以不依靠主函数调用直接运行,(在左侧有小绿色三角,点击即可运行)
init()方法创建连接
userDao中的findAll()方法会通过访问数据库执行IUserDao接口写在注解中的sql语句,查询结果返回到user中

相关文章

网友评论

      本文标题:在IDEA中用MyBatis实现简单的增删改查

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