Mybatis的CRUD操作大全(传统dao开发)

1. 创建数据库

小编已经在数据库中创建了用户数据库

接下来我们创建学生表

USER `user`;
CREATE TABLE `student`(
`uid` INT(12) NOT NULL AUTO_INCREMENT,
`uname` VARCHAR(32) NOT NULL,
`password` INT(16) NOT NULL,
`birthday` DATE NOT NULL,
PRIMARY KEY(`uid`)
)ENGINE=INNODB DEFAULT CHARSET=utf8

创建成功如下
在这里插入图片描述

2. 配置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>com.itheima</groupId>
    <artifactId>day01_eesy_02mybatis_annotation</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <dependencies>
        <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.12</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.10</version>
        </dependency>
    </dependencies>

</project>        
      

在创建项目的时候,只需要记得导入junit,apectjweaver,sql-connector-java,spring-test,spring-context,spring-context,spring-tx,spring-jdbc,commons-dbutilsjar包即可

3. 注册数据库的驱动器

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/user
jdbc.username=root
jdbc.password=root

4. 配置log4j.properties

# Set root category priority to 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.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
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

5. 配置文件

<?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">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/user"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
    <!--配置映射文件的位置-->
    <mappers>
        <mapper resource="com/ithemo/dao/StudentDao.xml"></mapper>
    </mappers>
</configuration>

6. 创建实体类

package com.ithemo.domain;

import java.io.Serializable;
import java.util.Date;

/**
 * 账户的实体类
 */
public class Student implements Serializable {
    private Integer uid;
    private String uname;
    private Float password;
    private Date birthday;

    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 Float getPassword() {
        return password;
    }

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

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Student{" +
                "uid=" + uid +
                ", uname='" + uname + '\'' +
                ", password=" + password +
                ", birthday=" + birthday +
                '}';
    }
}

7. 创建持久层接口

package com.itheima.dao;
import com.itheima.domain.Student;
/**
 * 账户的持久层接口
 */
public interface StudentDao {
    /**
     * 根据Id查询账户
     * @param uid
     * @return
     */
    Student findStudentById(Integer uid);
    /**
     * 根据名称查询账户
     * @param 
     * @return
     */
    Student findStudnetByUname(String StudnetUname);
    /**
     * 更新账户
     * @param student
     */
    void updateStudent(Student student);

    /**
     * 根据id删除账户
     * @param uid
     * @return
     */
    void deteleId(Integer uid);
}

查询一个

创建持久层接口的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
        namespace="com.ithemo.dao.StudentDao">
    <select id="findStudentById" parameterType="INT" resultType="com.ithemo.domain.Student">
        select * from student where uid=#{uid}
    </select>
</mapper>
测试类
package com.ithemo.test;

import com.ithemo.dao.StudentDao;
import com.ithemo.domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;

/**
 * 使用Junit单元测试:测试我们的配置
 */

public class StudentServiceTest {
    @Test
    public void findStudentById() throws Exception {
        //1.读取配置文件,生产字节输入流
        InputStream in = Resources.getResourceAsStream("MapConfig.xml");
        //2.获取SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
       //3.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4.获取代理对象
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        //5.执行查询
        Student studentById = mapper.findStudentById(1);
        System.out.println(studentById);

    }
}
结果截图

在这里插入图片描述
在这里插入图片描述

模糊查询

创建持久层接口的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
        namespace="com.ithemo.dao.StudentDao">
    <select id="findStudnetByUname" parameterType="String" resultType="com.ithemo.domain.Student">
        select * from student where uname like #{uname}
    </select>
</mapper>
测试类
package com.ithemo.test;

import com.ithemo.dao.StudentDao;
import com.ithemo.domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;
import java.util.List;

/**
 * 使用Junit单元测试:测试我们的配置
 */

public class StudentServiceTest {
    @Test
    public void findStudentById() throws Exception {
        //1.读取配置文件,生产字节输入流
        InputStream in = Resources.getResourceAsStream("MapConfig.xml");
        //2.获取SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
       //3.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4.获取代理对象
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        //5.根据名称查询
        List<Student> studnetByUname = studentDao.findStudnetByUname("%花%");
        for (Student user:studnetByUname) {
            System.out.println(user);
        }
    }
}
结果截图

在这里插入图片描述
在这里插入图片描述

另一种模糊查询

创建持久层接口的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
        namespace="com.ithemo.dao.StudentDao">
    <select id="findStudnetByUname" parameterType="String" resultType="com.ithemo.domain.Student">
        select * from student where uname like '%${value}%'
    </select>
</mapper>
测试类
package com.ithemo.test;

import com.ithemo.dao.StudentDao;
import com.ithemo.domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;
import java.util.List;

/**
 * 使用Junit单元测试:测试我们的配置
 */

public class StudentServiceTest {
    @Test
    public void findStudentById() throws Exception {
        //1.读取配置文件,生产字节输入流
        InputStream in = Resources.getResourceAsStream("MapConfig.xml");
        //2.获取SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
       //3.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4.获取代理对象
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        //5.根据名称查询
        List<Student> student  = studentDao.findStudnetByUname("花");
        for (Student student1:student) {
            System.out.println(student1);
        }
    }
}


结果截图

在这里插入图片描述
在这里插入图片描述

保存操作

创建持久层接口的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
        namespace="com.ithemo.dao.StudentDao">
    <insert id="updateStudent" parameterType="com.ithemo.domain.Student">
        insert into student(uid,uname,password,birthday)values(#{uid},#{uname},#{password},#{birthday})
    </insert>
</mapper>
测试类
package com.ithemo.test;

import com.ithemo.dao.StudentDao;
import com.ithemo.domain.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;
import java.util.Date;

/**
 * 使用Junit单元测试:测试我们的配置
 */

public class MaybatisTest {
    @Test
    public void findStudentById() throws Exception {
        Student student=new Student();
        student.setUid(7);
        student.setUsername("理想");
        student.setPassword(123400F);
        student.setBirthday(new Date());
        //1.读取配置文件,生产字节输入流
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4.获取代理对象
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        //5.执行查询
        mapper.updateStudent(student);
        sqlSession.commit();
        System.out.println(student);
    }
}
结果截图

在这里插入图片描述
在这里插入图片描述

删除操作

创建持久层接口的映射文件
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper
        namespace="com.ithemo.dao.StudentDao">

    <delete id="deteleId" parameterType="java.lang.Integer" >
        delete  from student where uid=#{uid}
    </delete>
</mapper>
测试类
package com.ithemo.test;

import com.ithemo.dao.StudentDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import java.io.InputStream;

/**
 * 使用Junit单元测试:测试我们的配置
 */

public class MaybatisTest {
    @Test
    public void findStudentById() throws Exception {

        //1.读取配置文件,生产字节输入流
        InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml");
        //2.获取SqlSessionFactory对象
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        //3.获取SqlSession对象
        SqlSession sqlSession = factory.openSession();
        //4.获取代理对象
        StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        //5.执行查询
         mapper.deteleId(7);
        sqlSession.commit();
    }
}
结果截图

在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

眼里只有码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值