題記:前面介紹了怎麼創建第一個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');
先看一看項目的目錄把,需要這樣把目錄創建好,如圖所示。
這個就項目的目錄,包需要自己創建,然後有UserService,User,UserMapper.xml都可以通過文件自動生成。
自動生成的文件下載地址我放在了GitHub上邊mybatisGenerator.zip就是自動生成文件的包
下載完成了包然後解壓會看見如下圖所示
紅色下標的就是要用到的,generatorConfig.xml就是要修改的東西,而運行命令就是在修改好了generatorConfig後再命令界面直接運行,下面一步步來:
因爲亂碼的問題,可以打開新建文本文檔.txt看,有註釋,大概需要修改的如圖所示:
如圖紅色下劃線所示的,都是需要修改的,結合註釋,很容易就改好了。
然後複製該段命令
java -jar mybatis-generator-core-1.3.7.jar -configfile generatorConfig.xml -overwrite
在generatorConfig.xml文件目錄下,什麼文件都不選擇,按住shift再點鼠標右鍵進入powershell窗口,鼠標右鍵粘貼,enter運行,就可以看到項目中多了3個文件如圖所示:
然後這樣就生成好了固定的文件了。
再配置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
如圖所示:
這樣就完成了簡單數據的查詢。
最後附上代碼(源碼,加sql文件)GitHub上可以直接下載實驗下載地址