项目搭建:springboot,mybatis, maven

创建一个基于Spring Boot、MyBatis和Maven的项目可以简化很多配置,因为Spring Boot自带了很多自动配置的功能。下面我将给出一个简单的示例来展示如何搭建这样一个项目。

### 1. 创建一个新的Spring Boot项目

你可以通过Spring Initializr(https://start.spring.io/)来生成项目结构,选择以下依赖:
- Spring Web
- MyBatis Framework
- MySQL Driver (或你使用的数据库驱动)
- Lombok (可选,用于减少样板代码)

或者,直接在IDE中创建一个Spring Boot项目,并手动添加这些依赖。

### 2. Maven `pom.xml` 文件

确保你的`pom.xml`文件中有如下依赖:

```xml
<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.example</groupId>
    <artifactId>springboot-mybatis-maven</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.0</version> <!-- 确保使用最新的稳定版本 -->
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <java.version>17</java.version>
    </properties>

    <dependencies>
        <!-- Spring Boot Starter Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- MyBatis Spring Boot Starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.1</version> <!-- 使用最新版本 -->
        </dependency>

        <!-- MySQL Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- Lombok (Optional) -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- Spring Boot Starter Test -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

### 3. 应用程序主类 `Application.java`

创建应用程序入口点:

```java
package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
```

### 4. 配置文件 `application.properties`

编辑`src/main/resources/application.properties`以配置数据源和其他属性:

```properties
# 数据库连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# MyBatis 配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.model

# 其他配置...
```

### 5. 创建实体类 `User.java`

```java
package com.example.model;

import lombok.Data;

@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    // Getters and Setters (Lombok will handle these)
}
```

### 6. 创建Mapper接口 `UserMapper.java`

```java
package com.example.mapper;

import com.example.model.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {

    @Select("SELECT * FROM users WHERE id = #{id}")
    User findById(@Param("id") Integer id);

    @Insert("INSERT INTO users(username, password) VALUES(#{username}, #{password})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(User user);

    @Update("UPDATE users SET username=#{username}, password=#{password} WHERE id=#{id}")
    void update(User user);

    @Delete("DELETE FROM users WHERE id=#{id}")
    void deleteById(@Param("id") Integer id);

    @Select("SELECT * FROM users")
    List<User> findAll();
}
```

### 7. 创建服务层 `UserService.java`

```java
package com.example.service;

import com.example.mapper.UserMapper;
import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Transactional
    public void saveOrUpdate(User user) {
        if (user.getId() == null) {
            userMapper.insert(user);
        } else {
            userMapper.update(user);
        }
    }

    public void delete(Integer id) {
        userMapper.deleteById(id);
    }

    public User findById(Integer id) {
        return userMapper.findById(id);
    }

    public List<User> findAll() {
        return userMapper.findAll();
    }
}
```

### 8. 创建控制器 `UserController.java`

```java
package com.example.controller;

import com.example.model.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping
    public List<User> listUsers() {
        return userService.findAll();
    }

    @GetMapping("/{id}")
    public User viewUser(@PathVariable("id") Integer id) {
        return userService.findById(id);
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
        userService.saveOrUpdate(user);
        return user;
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable("id") Integer id, @RequestBody User user) {
        user.setId(id);
        userService.saveOrUpdate(user);
        return user;
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable("id") Integer id) {
        userService.delete(id);
    }
}
```

### 9. Mapper XML文件(如果需要)

如果你的SQL查询比较复杂,可能需要编写XML映射文件。这些文件应该放在`src/main/resources/mapper/`目录下,并且命名规则应与Mapper接口相匹配,例如`UserMapper.xml`。

```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.mapper.UserMapper">

    <!-- Example of a complex SQL query -->
    <select id="findAll" resultType="com.example.model.User">
        SELECT * FROM users
    </select>

</mapper>
```

### 注意事项
- 如果你使用了`@Mapper`注解,确保你的Spring Boot应用扫描到了这个注解。
- 确认数据库表结构与实体类字段一致,并检查数据库连接信息是否正确。
- 根据实际情况调整包名、路径以及其他细节。

以上就是一个基本的Spring Boot + MyBatis + Maven项目的搭建过程。希望这个例子能够帮助你开始构建自己的应用程序。如果有任何问题或需要进一步的帮助,请随时提问!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/diannao/62948.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

详解Java数据库编程之JDBC

目录 首先创建一个Java项目 在Maven中央仓库下载mysql connector的jar包 针对MySQL版本5 针对MySQL版本8 下载之后&#xff0c;在IDEA中创建的项目中建立一个lib目录&#xff0c;然后把刚刚下载好的jar包拷贝进去&#xff0c;然后右键刚刚添加的jar包&#xff0c;点击‘添…

网络(TCP)

目录 TCP socket API 详解 套接字有哪些类型&#xff1f;socket有哪些类型&#xff1f; 图解TCP四次握手断开连接 图解TCP数据报结构以及三次握手&#xff08;非常详细&#xff09; socket缓冲区以及阻塞模式详解 再谈UDP和TCP bind(): 我们的程序中对myaddr参数是这样…

【笔记】离散数学 1-3 章

1. 数理逻辑 1.1 命题逻辑的基本概念 1.1.1 命题的概念 命题&#xff08;Proposition&#xff09;&#xff1a;是一个陈述句&#xff0c;它要么是真的&#xff08;true&#xff09;&#xff0c;要么是假的&#xff08;false&#xff09;&#xff0c;但不能同时为真和假。例如…

【Linux篇】权限管理 - 用户与组权限详解

一. 什么是权限&#xff1f; 首先权限是限制人的。人 真实的人 身份角色 权限 角色 事物属性 二. 认识人–用户 Linux下的用户分为超级用户和普通用户 root :超级管理员&#xff0c;几乎不受权限的约束普通用户 :受权限的约束超级用户的命令提示符是#&#xff0c;普通用…

【机器学习】机器学习的基本分类-监督学习-决策树-C4.5 算法

C4.5 是由 Ross Quinlan 提出的决策树算法&#xff0c;是对 ID3 算法的改进版本。它在 ID3 的基础上&#xff0c;解决了以下问题&#xff1a; 处理连续型数据&#xff1a;支持连续型特征&#xff0c;能够通过划分点将连续特征离散化。处理缺失值&#xff1a;能够在特征值缺失的…

运维之网络安全抓包—— WireShark 和 tcpdump

为什么要抓包&#xff1f;何为抓包&#xff1f; 抓包&#xff08;packet capture&#xff09;就是将网络传输发送与接收的数据包进行截获、重发、编辑、转存等操作&#xff0c;也用来检查网络安全。抓包也经常被用来进行数据截取等。为什么要抓包&#xff1f;因为在处理 IP网络…

MongoDB 索引类型详解

MongoDB 索引类型详解 在 MongoDB 中&#xff0c;索引是提高查询效率、优化数据库性能的重要手段。MongoDB 支持多种类型的索引&#xff0c;每种索引类型适用于不同的查询需求和场景。本文将详细介绍 MongoDB 中几种常见的索引类型、示例及其限制。 1. 单字段索引&#xff08…

2023年MathorCup高校数学建模挑战赛—大数据竞赛B题电商零售商家需求预测及库存优化问题求解全过程文档及程序

2023年MathorCup高校数学建模挑战赛—大数据竞赛 B题 电商零售商家需求预测及库存优化问题 原题再现&#xff1a; 电商平台存在着上千个商家&#xff0c;他们会将商品货物放在电商配套的仓库&#xff0c;电商平台会对这些货物进行统一管理。通过科学的管理手段和智能决策&…

cocotb pytest

打印python中的print &#xff0c; 应该使用 pytest -s pytest --junitxmltest_report.xml --htmlreport.html

【Linux】进程间关系与守护进程

&#x1f30e;进程间关系与守护进程 文章目录&#xff1a; 进程间关系与守护进程 进程组     会话       认识会话       会话ID       创建会话 控制终端     作业控制       作业(job)和作业控制(Job Control)       作业号及作业过程…

RuoYi-Vue部署到Linux服务器(Jar+Nginx)

一、本地环境准备 源码下载、本地Jdk及Node.js环境安装,参考以下文章。 附:RuoYi-Vue下载与运行 二、服务器环境准备 1.安装Jdk 附:JDK8下载安装与配置环境变量(linux) 2.安装MySQL 附:MySQL8免安装版下载安装与配置(linux) 3.安装Redis 附:Redis下载安装与配置(…

QT5.14 QML串口助手

基于 QML的 串口调试助手 这个代码有缺失&#xff0c;补了部分代码 ASCII HEX 工程共享&#xff0c; Qt版本 5.14.1 COM_QML 通过百度网盘分享的文件&#xff1a;COM_QML.zip 链接&#xff1a;https://pan.baidu.com/s/1MH2d6gIPDSoaX-syVWZsww?pwd5tge 提取码&#xff1a;…

IOS ARKit进行图像识别

先讲一下基础控涧&#xff0c;资源的话可以留言&#xff0c;抽空我把它传到GitHub上&#xff0c;这里没写收积分&#xff0c;竟然充值才能下载&#xff0c;我下载也要充值&#xff0c;牛&#xff01; ARSCNView 可以理解画布或者场景 1 配置 ARWorldTrackingConfiguration AR追…

常用排查工具使用

1.spy++ Microsoft Spy++是一个非常好的查看Windows操作系统的窗口、消息、进程、线程信息的工具,简单易用,功能强大。 在vs的工具中默认安装,还可以监控到隐层窗口,通过查看窗口的属性可以获得更多信息,包括规格、窗口、类、进程等信息,可以帮助排查相关窗口的问题。 2…

“Encrypt”属性设置为“true”且 “trustServerCertificate”属性设置为“false”,但驱动程序无法使用安全套接字层 (SSL) 加密与 SQL Server 建立安全

com.microsoft.sqlserver.jdbc.SQLServerException: “Encrypt”属性设置为“true”且 “trustServerCertificate”属性设置为“false”&#xff0c;但驱动程序无法使用安全套接字层 (SSL) 加密与 SQL Server 建立安全连接:错误:PKIX path building failed: sun.security.provi…

【RK3588 Linux 5.x 内核编程】-内核高分辨率定时器

内核高分辨率定时器 文章目录 内核高分辨率定时器1、高分辨率定时器介绍2、高分辨率定时器API2.1 初始化定时器2.2 启动定时器2.3 停止定时器2.4 改变定时器超时时间2.5 定时器状态检查3、驱动实现4、驱动验证在前面的文章中,我们知道了如果在Linux内核中使用定时器。本文将详…

C语言第十五周课——课堂练习

目录 1.输出特定图形 2.求三个数的最小值 3.思考题 1.输出特定图形 要求&#xff1a;输出下面形状在控制台 * * * * * * * * * * * * * * * #include <stdio.h> int main() {int i, j;// 外层循环控制行数for (i 1; i < 5; i){// 内层循环控制每行的星号个数for (…

数据结构 (20)二叉树的遍历与线索化

一、二叉树的遍历 遍历是对树的一种最基本的运算&#xff0c;所谓遍历二叉树&#xff0c;就是按一定的规则和顺序走遍二叉树的所有节点&#xff0c;使每一个节点都被访问一次&#xff0c;而且只被访问一次。二叉树的遍历方式主要有四种&#xff1a;前序遍历、中序遍历、后序遍历…

sscanf与sprintf函数

本期介绍&#x1f356; 主要介绍&#xff1a;sscanf()、sprintf()这对输入/输出函数&#xff0c;并详细讲解了这两个函数的应用场景。 概述&#x1f356; 在C语言的输出和输入库中&#xff0c;有三对及其相似的库函数&#xff1a;printf()、scanf()、fprintf()、fscanf()、spri…

基于链表的基础笔试/面试题

1. 反转链表 问题描述&#xff1a;反转一个单向链表。 示例&#xff1a; 输入&#xff1a;1 → 2 → 3 → 4 → 5 输出&#xff1a;5 → 4 → 3 → 2 → 1 class ListNode {int val;ListNode next;ListNode(int x) {val x;} }public class LinkedList {public ListNode …