欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

最简单易懂的用ideal springboot Mybatis写的第一个查询数据库实验

程序员文章站 2022-05-03 13:16:58
...

题记:前面介绍了怎么创建第一个hello world,现在写第一个查询数据库的实验。文章最后附上源码。

先创建好数据如下代码,数据名test1,表名test1

/*
MySQL Data Transfer
Source Host: localhost
Source Database: test1
Target Host: localhost
Target Database: test1
Date: 2019/12/2 17:14:00
*/

SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for test1
-- ----------------------------
CREATE TABLE `test1` (
  `id` int(10) NOT NULL default '0',
  `password` varchar(50) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records 
-- ----------------------------
INSERT INTO `test1` VALUES ('123', '123');
INSERT INTO `test1` VALUES ('234', 'root');

先看一看项目的目录把,需要这样把目录创建好,如图所示。

最简单易懂的用ideal springboot Mybatis写的第一个查询数据库实验

这个就项目的目录,包需要自己创建,然后有UserService,User,UserMapper.xml都可以通过文件自动生成。

自动生成的文件下载地址我放在了GitHub上边mybatisGenerator.zip就是自动生成文件的包

下载完成了包然后解压会看见如下图所示

最简单易懂的用ideal springboot Mybatis写的第一个查询数据库实验

红色下标的就是要用到的,generatorConfig.xml就是要修改的东西,而运行命令就是在修改好了generatorConfig后再命令界面直接运行,下面一步步来:

因为乱码的问题,可以打开新建文本文档.txt看,有注释,大概需要修改的如图所示:

最简单易懂的用ideal springboot Mybatis写的第一个查询数据库实验

如图红色下划线所示的,都是需要修改的,结合注释,很容易就改好了。

然后复制该段命令

java -jar mybatis-generator-core-1.3.7.jar -configfile generatorConfig.xml -overwrite

在generatorConfig.xml文件目录下,什么文件都不选择,按住shift再点鼠标右键进入powershell窗口,鼠标右键粘贴,enter运行,就可以看到项目中多了3个文件如图所示:

最简单易懂的用ideal springboot Mybatis写的第一个查询数据库实验

然后这样就生成好了固定的文件了。

再配置application.property如下:

server.port=8090  
#端口号

mybatis.mapper-locations=classpath:mapper/*.xml

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test1
#  你的数据库表,这里我在数据库里面有个叫test1的表
spring.datasource.username=root
#  你的数据库账号
spring.datasource.password=root
#  你的数据库密码
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#  如果这里报错误可以把cj去掉试试

User类

package com.example.demo.entity;

public class User {
    private Integer id;

    private String password;

    public Integer getId() {
        return id;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }


}

UserService类

package com.example.demo.service;

import com.example.demo.entity.User;

import java.util.List;

public interface UserService {

    String hellow();

    public String hellowWorld();

    int deleteByPrimaryKey(Integer id);

    int insert(com.example.demo.entity.User record);

    int insertSelective(com.example.demo.entity.User record);

    com.example.demo.entity.User selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(com.example.demo.entity.User record);

    int updateByPrimaryKey(com.example.demo.entity.User record);

    List<User> selectAll();
}
UserServicelmp类
package com.example.demo.serviceImp;

import com.example.demo.dao.UserMapper;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.List;


@Service
@Transactional

public class UserServicelmp implements UserService{
        protected static Logger logger= LoggerFactory.getLogger(UserServicelmp.class);
    @Autowired(required = false)
    UserMapper userMapper;

    @Override
    public String hellow() {
        logger.info("调用了hello");
        return "Hello world";
    }

    @Override
    public String hellowWorld() {
        return null;
    }

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return 0;
    }

    @Override
    public int insert(User record) {
        return 0;
    }

    @Override
    public int insertSelective(User record) {
        return 0;
    }

    @Override
    public User selectByPrimaryKey(Integer id) {
        return null;
    }

    @Override
    public int updateByPrimaryKeySelective(User record) {
        return 0;
    }

    @Override
    public int updateByPrimaryKey(User record) {
        return 0;
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectAll();
    }
}

这里说一下,你直接再UserServicelmp后面写implements,然后根据提示就会创建这些return 0 的东西了。

hellowWorld测试类
package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.mybatis.spring.annotation.MapperScans;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/test")
public class hellowWorld {
@Autowired(required = false)
UserService userService;

    @GetMapping("/hellow")
    public String hellow() {
        return "hellow world";
    }
        @GetMapping("/getAll")
        public List<User> getAll(){
                return userService.selectAll();
        }



}

UserMapper.xml

<?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.example.demo.dao.UserMapper">
  <resultMap id="BaseResultMap" type="com.example.demo.entity.User">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="password" jdbcType="VARCHAR" property="password" />
  </resultMap>
  <sql id="Base_Column_List">
    id, password
  </sql>
  <select id="selectAll" resultType="com.example.demo.entity.User">
        select *
        from test1
    </select>
  <select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
    select
    <include refid="Base_Column_List" />
    from test1
    where id = #{id,jdbcType=INTEGER}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
    delete from test1
    where id = #{id,jdbcType=INTEGER}
  </delete>
  <insert id="insert" parameterType="com.example.demo.entity.User">
    insert into test1 (id, password)
    values (#{id,jdbcType=INTEGER}, #{password,jdbcType=VARCHAR})
  </insert>
  <insert id="insertSelective" parameterType="com.example.demo.entity.User">
    insert into test1
    <trim prefix="(" suffix=")" suffixOverrides=",">
      <if test="id != null">
        id,
      </if>
      <if test="password != null">
        password,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides=",">
      <if test="id != null">
        #{id,jdbcType=INTEGER},
      </if>
      <if test="password != null">
        #{password,jdbcType=VARCHAR},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.example.demo.entity.User">
    update test1
    <set>
      <if test="password != null">
        password = #{password,jdbcType=VARCHAR},
      </if>
    </set>
    where id = #{id,jdbcType=INTEGER}
  </update>
  <update id="updateByPrimaryKey" parameterType="com.example.demo.entity.User">
    update test1
    set password = #{password,jdbcType=VARCHAR}
    where id = #{id,jdbcType=INTEGER}
  </update>
</mapper>

其实这里面就写了一句,其他的都是自动生成的

<select id="selectAll" resultType="com.example.demo.entity.User">
        select *
        from test1
    </select>

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.37</version>
                <scope>runtime</scope>
            </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

这样就完成了,然后启动项目,在浏览器运行http://localhost:8090/test/getAll

如图所示:

最简单易懂的用ideal springboot Mybatis写的第一个查询数据库实验

这样就完成了简单数据的查询。

最后附上代码(源码,加sql文件)GitHub上可以直接下载实验下载地址