準備
MySQL
命令
$ docker pull mysql
$ docker run --name local-mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 -d mysql
Maven
相關(guān)地址
下載地址:
https://maven.apache.org/
maven配置方法地址:
https://developer.aliyun.com/mvn/guide
倉庫搜索地址:
https://mvnrepository.com/
https://repo.maven.apache.org/
maven
本地配置conf/settings.xml
<!-- TAG··· -->
<!-- 指定下載依賴到本地的路徑 -->
<localRepository>${user.home}/Documents/AAA-PLee/maven/repository</localRepository>
<!-- TAG··· -->
<!-- 配置為阿里云公共倉庫 -->
<mirror>
<id>aliyunmaven</id>
<mirrorOf>*</mirrorOf>
<name>阿里云公共倉庫</name>
<url>https://maven.aliyun.com/repository/public</url>
</mirror>
<!-- TAG··· -->
下載idea
并配置本地環(huán)境maven
Maven
構(gòu)建生命周期
-
Maven
的構(gòu)建生命周期
包括三個階段
:clean
、build
和site
-
clean
:清理項目,刪除之前的編譯結(jié)果和構(gòu)建產(chǎn)生的文件。 -
build
:構(gòu)建項目,包括編譯、測試、打包等操作。 -
site
:生成項目文檔和報告,例如測試報告、代碼覆蓋率報告等。
-
- 每個階段都包含了一些插件和目標,
Maven
會按照預(yù)定義的順序依次執(zhí)行。例如,在build
階段,Maven
會依次執(zhí)行以下目標:-
validate
:驗證項目是否正確。 -
compile
:編譯項目源代碼。 -
test
:運行項目的測試用例。 -
package
:將項目打包成jar或war文件。 -
verify
:驗證打包結(jié)果是否正確。 -
install
:將打包結(jié)果安裝到本地Maven倉庫。 -
deploy
:將打包結(jié)果部署到遠程Maven倉庫。
-
idea所需插件下載
EasyCode
用于快速生成與數(shù)據(jù)庫相關(guān)的項目目錄和代碼
MyBatisPlus
用于
java
與sql.xml
之間的跳轉(zhuǎn)
idea創(chuàng)建項目
配置 Server URL
地址:https://start.aliyun.com/
填寫項目相關(guān)信息
創(chuàng)建項目成功(運行并測試)
idea測試能否正常連接MySQL
創(chuàng)建數(shù)據(jù)庫表
添加項目內(nèi)連接MySQL的配置
搜索連接MySQL使用的依賴包
編寫連接數(shù)據(jù)庫配置文件
在pom.xml
中引入MySQL依賴包
(別忘了Load Maven Changes
)
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
創(chuàng)建并編寫application.yml
路徑:
user/src/main/resources/application.yml
server:
port: 8000
spring:
application:
name: user-service
datasource:
url: jdbc:mysql://127.0.0.1:3306/java_app
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
利用插件EasyCode快速創(chuàng)建操作數(shù)據(jù)庫相關(guān)代碼
查看創(chuàng)建完成后的項目目錄結(jié)構(gòu)
Java
應(yīng)用程序通常使用以下幾個組件來組織代碼
這些組件之間的關(guān)系通常是
Controller
調(diào)用Service
,Service
定義impl
文件夾內(nèi)的業(yè)務(wù)實現(xiàn)類
,業(yè)務(wù)實現(xiàn)類
調(diào)用DAO
,DAO
操作Mapper
中的SQL語句
,Entity
表示數(shù)據(jù)庫表結(jié)構(gòu)實體類
簡單來說,
Controller
用于接收用戶請求,Service
實現(xiàn)業(yè)務(wù)邏輯,DAO
操作數(shù)據(jù)庫,Entity
表示數(shù)據(jù)庫表結(jié)構(gòu)
在
/service/impl/xxx.java
中實現(xiàn)具體業(yè)務(wù)邏輯在
/resources/mapper/xxx.xml
中添加操作數(shù)據(jù)的sql
語句
-
Controller
:控制器,用于接收用戶請求并調(diào)用相應(yīng)的處理方法來處理請求,然后返回響應(yīng)結(jié)果。通常使用Spring MVC
框架來實現(xiàn)。 -
Service
:服務(wù)層,用于實現(xiàn)業(yè)務(wù)邏輯,調(diào)用DAO
進行數(shù)據(jù)操作。通常包含接口和實現(xiàn)類。 -
DAO
:數(shù)據(jù)訪問對象,用于操作數(shù)據(jù)庫。通常使用MyBatis
、Hibernate
等框架來實現(xiàn)。 -
Entity
:實體類,用于表示數(shù)據(jù)庫中的表結(jié)構(gòu)。通常包含類屬性和對應(yīng)的getter/setter
方法。
解決項目中導(dǎo)入庫報錯問題
利用 https://mvnrepository.com/
搜索解決
<!-- 解決完成后的pom.xml -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
嘗試運行(報錯:沒有引入對應(yīng)版本)
<!-- <dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>3.1.0</version>
</dependency> -->
<!-- 修改為 -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
嘗試運行(缺少 @MapperScan
注解)
注意:
盡量選擇使用量大的依賴包
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
// user/src/main/java/com/example/user/UserApplication.java
package com.example.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan(basePackages = "com.example.user.dao")
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
- @SpringBootApplication注解是一個組合注解,它的作用是標記一個Spring
Boot應(yīng)用程序的主類。它包括三個注解:@Configuration
,@EnableAutoConfiguration
和@ComponentScan
- @Configuration:將該類標記為Spring應(yīng)用程序上下文中的一個bean定義的源。即在該類中定義的bean可以被Spring容器管理。
- @EnableAutoConfiguration:自動配置Spring Boot應(yīng)用程序所需的Bean。
- @ComponentScan:掃描應(yīng)用程序中的其他組件,例如控制器、服務(wù)和存儲庫。
- @MapperScan是MyBatis框架中的一個注解,它的作用是掃描指定的包路徑,找到所有標記了@Mapper注解的接口,并將這些接口創(chuàng)建成MyBatis的Mapper接口實現(xiàn)類
- 可以在需要使用Mapper的地方自動注入這些Mapper實現(xiàn)類的實例,從而方便地訪問數(shù)據(jù)庫。
嘗試運行(運行成功,若運行后立即結(jié)束,有可能為未引入spring-boot-starter-web
包)
嘗試引入即可
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
最終pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
訪問接口
請求失敗
解決報錯(告訴MyBatis
去哪里找SQL
語句)
mybatis:
mapper-locations: classpath:**/mapper/*.xml
重新運行并請求
文章來源:http://www.zghlxwxcb.cn/news/detail-727703.html
完整源碼
目錄結(jié)構(gòu)
文章來源地址http://www.zghlxwxcb.cn/news/detail-727703.html
引入依賴:user/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>
<groupId>com.example</groupId>
<artifactId>user</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>user</name>
<description>user</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.6.13</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.example.user.UserApplication</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
服務(wù)相關(guān)配置:user/src/main/resources/application.yml
server:
port: 8000
spring:
application:
name: user-service
datasource:
url: jdbc:mysql://127.0.0.1:3306/java_app
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:**/mapper/*.xml
入口:user/src/main/java/com/example/user/UserApplication.java
package com.example.user;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.mybatis.spring.annotation.MapperScan;
@SpringBootApplication
@MapperScan(basePackages = "com.example.user.dao")
public class UserApplication {
public static void main(String[] args) {
SpringApplication.run(UserApplication.class, args);
}
}
(User)表控制層:user/src/main/java/com/example/user/controller/UserController.java
package com.example.user.controller;
import com.example.user.entity.User;
import com.example.user.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
/**
* (User)表控制層
*
* @author makejava
* @since 2023-06-12 14:13:44
*/
@RestController
@RequestMapping("user")
public class UserController {
/**
* 服務(wù)對象
*/
@Resource
private UserService userService;
/**
* 分頁查詢
*
* @param user 篩選條件
* @param pageRequest 分頁對象
* @return 查詢結(jié)果
*/
@GetMapping
public ResponseEntity<Page<User>> queryByPage(User user, PageRequest pageRequest) {
return ResponseEntity.ok(this.userService.queryByPage(user, pageRequest));
}
/**
* 通過主鍵查詢單條數(shù)據(jù)
*
* @param id 主鍵
* @return 單條數(shù)據(jù)
*/
@GetMapping("{id}")
public ResponseEntity<User> queryById(@PathVariable("id") String id) {
return ResponseEntity.ok(this.userService.queryById(id));
}
/**
* 新增數(shù)據(jù)
*
* @param user 實體
* @return 新增結(jié)果
*/
@PostMapping
public ResponseEntity<User> add(User user) {
return ResponseEntity.ok(this.userService.insert(user));
}
/**
* 編輯數(shù)據(jù)
*
* @param user 實體
* @return 編輯結(jié)果
*/
@PutMapping
public ResponseEntity<User> edit(User user) {
return ResponseEntity.ok(this.userService.update(user));
}
/**
* 刪除數(shù)據(jù)
*
* @param id 主鍵
* @return 刪除是否成功
*/
@DeleteMapping
public ResponseEntity<Boolean> deleteById(String id) {
return ResponseEntity.ok(this.userService.deleteById(id));
}
}
(User)表服務(wù)接口:user/src/main/java/com/example/user/service/UserService.java
package com.example.user.service;
import com.example.user.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
/**
* (User)表服務(wù)接口
*
* @author makejava
* @since 2023-06-12 14:13:49
*/
public interface UserService {
/**
* 通過ID查詢單條數(shù)據(jù)
*
* @param id 主鍵
* @return 實例對象
*/
User queryById(String id);
/**
* 分頁查詢
*
* @param user 篩選條件
* @param pageRequest 分頁對象
* @return 查詢結(jié)果
*/
Page<User> queryByPage(User user, PageRequest pageRequest);
/**
* 新增數(shù)據(jù)
*
* @param user 實例對象
* @return 實例對象
*/
User insert(User user);
/**
* 修改數(shù)據(jù)
*
* @param user 實例對象
* @return 實例對象
*/
User update(User user);
/**
* 通過主鍵刪除數(shù)據(jù)
*
* @param id 主鍵
* @return 是否成功
*/
boolean deleteById(String id);
}
(User)表服務(wù)實現(xiàn)類:user/src/main/java/com/example/user/service/impl/UserServiceImpl.java
package com.example.user.service.impl;
import com.example.user.entity.User;
import com.example.user.dao.UserDao;
import com.example.user.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import javax.annotation.Resource;
/**
* (User)表服務(wù)實現(xiàn)類
*
* @author makejava
* @since 2023-06-12 14:13:50
*/
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
/**
* 通過ID查詢單條數(shù)據(jù)
*
* @param id 主鍵
* @return 實例對象
*/
@Override
public User queryById(String id) {
return this.userDao.queryById(id);
}
/**
* 分頁查詢
*
* @param user 篩選條件
* @param pageRequest 分頁對象
* @return 查詢結(jié)果
*/
@Override
public Page<User> queryByPage(User user, PageRequest pageRequest) {
long total = this.userDao.count(user);
return new PageImpl<>(this.userDao.queryAllByLimit(user, pageRequest), pageRequest, total);
}
/**
* 新增數(shù)據(jù)
*
* @param user 實例對象
* @return 實例對象
*/
@Override
public User insert(User user) {
this.userDao.insert(user);
return user;
}
/**
* 修改數(shù)據(jù)
*
* @param user 實例對象
* @return 實例對象
*/
@Override
public User update(User user) {
this.userDao.update(user);
return this.queryById(user.getId());
}
/**
* 通過主鍵刪除數(shù)據(jù)
*
* @param id 主鍵
* @return 是否成功
*/
@Override
public boolean deleteById(String id) {
return this.userDao.deleteById(id) > 0;
}
}
(User)表數(shù)據(jù)庫訪問層:user/src/main/java/com/example/user/dao/UserDao.java
package com.example.user.dao;
import com.example.user.entity.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.data.domain.Pageable;
import java.util.List;
/**
* (User)表數(shù)據(jù)庫訪問層
*
* @author makejava
* @since 2023-06-12 14:13:45
*/
public interface UserDao {
/**
* 通過ID查詢單條數(shù)據(jù)
*
* @param id 主鍵
* @return 實例對象
*/
User queryById(String id);
/**
* 查詢指定行數(shù)據(jù)
*
* @param user 查詢條件
* @param pageable 分頁對象
* @return 對象列表
*/
List<User> queryAllByLimit(User user, @Param("pageable") Pageable pageable);
/**
* 統(tǒng)計總行數(shù)
*
* @param user 查詢條件
* @return 總行數(shù)
*/
long count(User user);
/**
* 新增數(shù)據(jù)
*
* @param user 實例對象
* @return 影響行數(shù)
*/
int insert(User user);
/**
* 批量新增數(shù)據(jù)(MyBatis原生foreach方法)
*
* @param entities List<User> 實例對象列表
* @return 影響行數(shù)
*/
int insertBatch(@Param("entities") List<User> entities);
/**
* 批量新增或按主鍵更新數(shù)據(jù)(MyBatis原生foreach方法)
*
* @param entities List<User> 實例對象列表
* @return 影響行數(shù)
* @throws org.springframework.jdbc.BadSqlGrammarException 入?yún)⑹强誏ist的時候會拋SQL語句錯誤的異常,請自行校驗入?yún)? */
int insertOrUpdateBatch(@Param("entities") List<User> entities);
/**
* 修改數(shù)據(jù)
*
* @param user 實例對象
* @return 影響行數(shù)
*/
int update(User user);
/**
* 通過主鍵刪除數(shù)據(jù)
*
* @param id 主鍵
* @return 影響行數(shù)
*/
int deleteById(String id);
}
(User)實體類:user/src/main/java/com/example/user/entity/User.java
package com.example.user.entity;
import java.io.Serializable;
/**
* (User)實體類
*
* @author makejava
* @since 2023-06-12 14:13:46
*/
public class User implements Serializable {
private static final long serialVersionUID = 264722085318530649L;
private String id;
private String name;
private Integer age;
private String sex;
private String phone;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
SQL:user/src/main/resources/mapper/UserDao.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.user.dao.UserDao">
<resultMap type="com.example.user.entity.User" id="UserMap">
<result property="id" column="id" jdbcType="VARCHAR"/>
<result property="name" column="name" jdbcType="VARCHAR"/>
<result property="age" column="age" jdbcType="INTEGER"/>
<result property="sex" column="sex" jdbcType="VARCHAR"/>
<result property="phone" column="phone" jdbcType="VARCHAR"/>
</resultMap>
<!--查詢單個-->
<select id="queryById" resultMap="UserMap">
select
id, name, age, sex, phone
from user
where id = #{id}
</select>
<!--查詢指定行數(shù)據(jù)-->
<select id="queryAllByLimit" resultMap="UserMap">
select
id, name, age, sex, phone
from user
<where>
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="name != null and name != ''">
and name = #{name}
</if>
<if test="age != null">
and age = #{age}
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
<if test="phone != null and phone != ''">
and phone = #{phone}
</if>
</where>
limit #{pageable.offset}, #{pageable.pageSize}
</select>
<!--統(tǒng)計總行數(shù)-->
<select id="count" resultType="java.lang.Long">
select count(1)
from user
<where>
<if test="id != null and id != ''">
and id = #{id}
</if>
<if test="name != null and name != ''">
and name = #{name}
</if>
<if test="age != null">
and age = #{age}
</if>
<if test="sex != null and sex != ''">
and sex = #{sex}
</if>
<if test="phone != null and phone != ''">
and phone = #{phone}
</if>
</where>
</select>
<!--新增所有列-->
<insert id="insert" keyProperty="id" useGeneratedKeys="true">
insert into user(name, age, sex, phone)
values (#{name}, #{age}, #{sex}, #{phone})
</insert>
<insert id="insertBatch" keyProperty="id" useGeneratedKeys="true">
insert into user(name, age, sex, phone)
values
<foreach collection="entities" item="entity" separator=",">
(#{entity.name}, #{entity.age}, #{entity.sex}, #{entity.phone})
</foreach>
</insert>
<insert id="insertOrUpdateBatch" keyProperty="id" useGeneratedKeys="true">
insert into user(name, age, sex, phone)
values
<foreach collection="entities" item="entity" separator=",">
(#{entity.name}, #{entity.age}, #{entity.sex}, #{entity.phone})
</foreach>
on duplicate key update
name = values(name),
age = values(age),
sex = values(sex),
phone = values(phone)
</insert>
<!--通過主鍵修改數(shù)據(jù)-->
<update id="update">
update user
<set>
<if test="name != null and name != ''">
name = #{name},
</if>
<if test="age != null">
age = #{age},
</if>
<if test="sex != null and sex != ''">
sex = #{sex},
</if>
<if test="phone != null and phone != ''">
phone = #{phone},
</if>
</set>
where id = #{id}
</update>
<!--通過主鍵刪除-->
<delete id="deleteById">
delete from user where id = #{id}
</delete>
</mapper>
到了這里,關(guān)于Java(一):創(chuàng)建 Spring Boot 項目并實現(xiàn)連接操作MySQL數(shù)據(jù)庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!