Spring Boot结合Mybatis的项目搭建及数据库增删改查操作

本文介绍了如何使用Spring Boot结合Mybatis搭建项目,并进行数据库的增删改查操作。从添加相关依赖,配置log4j和mybatis,到创建实体类、DAO层、Mapper文件和Controller层,详细讲解每个步骤。通过Postman测试接口,可以观察控制台输出及数据库的实际变化。
摘要由CSDN通过智能技术生成

引入依赖

 <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.15</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.16</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.6.4</version>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.8.2</version>
            <scope>test</scope>
        </dependency>

在pom.xml文件build标签中添加

<resources>
            <!-- 编译之后包含xml   -->
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>

在resource目录下创建log4j.propertise

spring.datasource.filters=stat,wall,log4j
# Global logging configuration
log4j.rootLogger=ERROR,stdout
# MyBatis logging configuration...
log4j.logger.net.biancheng=DEBUG
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

在resource目录下创建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>

    <settings>
    <setting name="logImpl" value="LOG4J" />
    </settings>

    <!-- 配置mybatis运行环境 -->
    <environments default="development">

    <environment id="development">
    <!-- 使用JDBC的事务管理 -->
    <transactionManager type="JDBC" />
    <dataSource type="POOLED">
        <!-- MySQL数据库驱动 -->
        <property name="driver" value="com.mysql.cj.jdbc.Driver" />
        <!-- 连接数据库的URL -->
        <property name="url" value="jdbc:mysql://localhost:3306/exam?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=GMT%2B8&amp;useSSL=false" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </dataSource>
</environment>
</environments>
    
</configuration>

(改成自己的数据库名字,用户名和密码)搭建就完成啦

整体结构如图

实体类Student继承Serializable


public class Student implements Serializable {
    private Integer id;
    private  String age;
    private String sex;
    private String name;
    private  String id_card;
    private String student_class;
    public Student(){

    }

    public Student(Integer id, String age, String sex, String name, String id_card, String student_class) {
        this.id = id;
        this.age = age;
        this.sex = sex;
        this.name = name;
        this.id_card = id_card;
        this.student_class = student_class;
    }

    public Integer getId() {
        return id;
    }

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

    public String getAge() {
        return age;
    }

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

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

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

    public String getId_card() {
        return id_card;
    }

    public void setId_card(String id_card) {
        this.id_card = id_card;
    }

    public String getStudent_class() {
        return student_class;
    }

    public void setStudent_class(String student_class) {
        this.student_class = student_class;
    }

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

查询所有操作 

 dao层


public interface StudentMapper {
    List<Student> selectAllStudent();

}

mapper文件

<?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="com.haha.demo.dao.StudentMapper">
    <!-- 查询所有网站信息 -->
    <select id="selectAllStudent"
            resultType="com.haha.demo.pojo.Student">
        select * from students
    </select>
</mapper>

controller层


@Controller
public class HelloController {
    @RequestMapping("/")
    @ResponseBody
    public String getHello() throws IOException {
        InputStream config = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
        SqlSession ss = ssf.openSession();
        StudentMapper pm = ss.getMapper(StudentMapper.class);
        List<Student> listWeb = pm.selectAllStudent();
        for (Student site : listWeb) {
            System.out.println(site);
        }
        ss.commit();
        ss.close();
        return "ok!";
    }
}

运行http://localhost:8080/  可以看到控制台的输出结果

删除操作

StudentMapper

public interface StudentMapper {
    //查询所有
   // List<Student> selectAllStudent();
    public void deleteStudent(Integer id);

}

mapper.xml 

<delete id="deleteStudent" >
        delete from students where id=#{id}
    </delete>

建个test文件(引入之前加入test依赖)


public class TestMybatis {
    @Test
    public void test()  throws Exception{
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        SqlSession session = sqlSessionFactory.openSession(true);
        try {

            //Mapper接口:获取Mapper接口的 代理实现类对象
            StudentMapper mapper = session.getMapper(StudentMapper.class);

            //4:删除操作
            Student student= new Student();
            mapper.deleteStudent(104);

        } finally {
            session.close();
        }
    }

}

运行test刷新数据库就会看到结果

根据id查询、添加、修改操作

接口


    /**
     * 根据id查询
   
     */
    public Student getStudentById(int id);

    /**
     * 增加
   
     */
    public Integer insertStudent(Student student);


    /**
     * 修改
    
     */
    public boolean updateStudent(Student student);

test 

 //1: 查询操作调用实际方法实现操作
            Student student = mapper.getStudentById(1);
            System.out.println(student);


            //2: 添加操作
            Student student = new Student();
            student.setLastname("t");
            student.setEmail("t@qq.com");
            Integer rows = mapper.insertStudent(student);
            System.out.println(rows);


            //3:修改操作
            Student student = new Student();
            student.setLastname("to");
            student.setEmail("t@163.com");
            boolean isupdate = mapper.updateStudent(student);
            System.out.println(isupdate);

mapper.xml

 <!--查询-->
    <select id="getEmployeeById" resultType="com.mybatislearn.entity.Employee">
        select * from tbl_employee where id = #{id}
    </select>
    
    <!--增加:useGeneratedKeys和keyProperty属性是设置自增长和自增长的字段的-->
    <insert id="insertEmployee" parameterType="com.mybatislearn.entity.Employee" useGeneratedKeys="true" keyProperty="id>
        INSERT INTO tbl_employee(lastname,email,gender) VALUES(#{lastname},#{email},#{gender})
    </insert>
    
    <!--修改-->
    <update id="updateEmployee" parameterType="com.mybatislearn.entity.Employee">
        UPDATE tbl_employee SET lastname=#{lastname},email=#{email},gender=#{gender} WHERE id=#{id}
    </update>
    

 运行test刷新数据库就会看到结果

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值