Java中CRUD的快速實(shí)現(xiàn)方法
Java 中的 CRUD(Create、Read、Update、Delete)操作是數(shù)據(jù)持久化的基礎(chǔ)操作,通常用于與數(shù)據(jù)庫交互。目前隨著技術(shù)發(fā)展,CRUD的開發(fā)越來越簡便。
涉及技術(shù)棧:Spring;Spring boot; Mybatis; Maven; Mybatis-plus
(數(shù)據(jù)庫需要自己去寫,至少得有一個(gè)吧)
(只提供到后端接口,沒有前端)
1.注解寫法下的CRUD
項(xiàng)目結(jié)構(gòu):

pojo/entity/domain:實(shí)體類,顧名思義里面存放的就是對應(yīng)數(shù)據(jù)庫的各種實(shí)體。如我這里里面有一個(gè)user類對應(yīng)數(shù)據(jù)庫中的用戶表。在這個(gè)實(shí)體類中存在它的屬性以及getter,setter,有參,無參,toString方法。
package com.imut.sccos.pojo;
public class User {
private Integer id;
private String username;
private String password;
private String userrole;
private String phone;
private String avatar;
private Integer isdelete;
public Integer getIsdelete() {
return isdelete;
}
public void setIsdelete(Integer isdelete) {
this.isdelete = isdelete;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserrole() {
return userrole;
}
public void setUserrole(String userrole) {
this.userrole = userrole;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public User(Integer id, String username, String password, String userrole, String phone, String avatar, Integer isdelete) {
this.id = id;
this.username = username;
this.password = password;
this.userrole = userrole;
this.phone = phone;
this.avatar = avatar;
this.isdelete = isdelete;
}
public User() {
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
", userrole='" + userrole + '\'' +
", phone='" + phone + '\'' +
", avatar='" + avatar + '\'' +
", isdelete=" + isdelete +
'}';
}
}其中getter,setter,有參,無參,toString方法可以用注解的方法來優(yōu)化省略不寫(就是注解給你寫了),具體如下:
引入依賴坐標(biāo)lombok:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>@Data // getter setter toString
@AllArgsConstructor // 有參構(gòu)造
@NoArgsConstructor // 無參構(gòu)造
public class Order {
private Integer id;
private Integer userId;
private Integer productId;
private Integer number;
private Double price;
private Double amount;
private String productName;
private String username;
}注意:如果有實(shí)體類報(bào)錯(cuò)最好不要用lombok,老實(shí)自己寫方法就好了。
controller層:這個(gè)地方主要是寫后端與前端鏈接的端口。接口一般有邏輯刪除、修改、全部查詢、條件查詢。
@RestController
@CrossOrigin//允許跨域訪問
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@GetMapping("/findUserByUsername")
public List<User> findUserByUsername(User user){
return userService.findUserByUsername(user);
}
@GetMapping("/findUserById")
public User findUserById(Integer id){
return userService.findUserById(id);
}
@RequestMapping("/editUser")
public int editUser(User user){
return userService.editUser(user);
}
}
service層:這里是實(shí)現(xiàn)具體業(yè)務(wù)的地方,主要分為接口和實(shí)現(xiàn)類。
public interface UserService {
public List<User> findUserByUsername(User user);
public User findUserById(Integer id);
public int editUser(User user);
}@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
@Override
public List<User> findUserByUsername(User user) {
return userMapper.findUserByUsername(user);
}
@Override
public User findUserById(Integer id) {
return userMapper.findUserById(id);
}
@Override
public int editUser(User user) {
if (user.getId() != null && user.getId() >0){
return userMapper.updateByPrimaryKeySelective( user);
}else{
return userMapper.insertSelective(user);
}
}
}注:注意這里的editUser,有人會(huì)問前面的接口為什么沒有添加呢?這里面進(jìn)行了判斷:如果在修改時(shí)能夠在數(shù)據(jù)庫中能夠獲取到該id,那它就是修改操作;如果查不到,那就是新增操作。
mapper層:這一層用來和數(shù)據(jù)庫進(jìn)行交互。分為接口和實(shí)現(xiàn)文件。
@Mapper
public interface UserMapper {
//新增和修改,如果有id就是修改,沒有則是新增
int insertSelective(User record);
int updateByPrimaryKeySelective(User record);
//根據(jù)id查詢
User findUserById(Integer id);
//根據(jù)名字,電話,角色模糊查詢,還包含了邏輯刪除
List<User> findUserByUsername(User user);
}
<?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.imut.sccos.mapper.UserMapper">
<resultMap id="BaseResultMap" type="com.imut.sccos.pojo.User">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="username" property="username" jdbcType="VARCHAR"/>
<result column="password" property="password" jdbcType="VARCHAR"/>
<result column="userrole" property="userrole" jdbcType="VARCHAR"/>
<result column="phone" property="phone" jdbcType="VARCHAR"/>
<result column="isdelete" property="isdelete" jdbcType="INTEGER"/>
<result column="avatar" property="avatar" jdbcType="VARCHAR"/>
</resultMap>
<sql id="Base_Column_List">
id, username, password, userrole, phone, isdelete, avatar
</sql>
<!--新增操作-->
<insert id="insertSelective" parameterType="com.imut.sccos.pojo.User">
insert into user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="username != null">
username,
</if>
<if test="password != null">
password,
</if>
<if test="userrole != null">
userrole,
</if>
<if test="phone != null">
phone,
</if>
<if test="isdelete != null">
isdelete,
</if>
<if test="avatar != null">
avatar,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="username != null">
#{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="userrole != null">
#{userrole,jdbcType=VARCHAR},
</if>
<if test="phone != null">
#{phone,jdbcType=VARCHAR},
</if>
<if test="isdelete != null">
#{isdelete,jdbcType=INTEGER},
</if>
<if test="avatar != null">
#{avatar,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<!--更新操作-->
<update id="updateByPrimaryKeySelective" parameterType="com.imut.sccos.pojo.User">
update user
<set>
<if test="username != null">
username = #{username,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="userrole != null">
userrole = #{userrole,jdbcType=VARCHAR},
</if>
<if test="phone != null">
phone = #{phone,jdbcType=VARCHAR},
</if>
<if test="isdelete != null">
isdelete = #{isdelete,jdbcType=INTEGER},
</if>
<if test="avatar != null">
avatar = #{avatar,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<!--條件查詢用戶信息,支持用戶名,電話,角色查詢-->
<select id="findUserByUsername" parameterType="com.imut.sccos.pojo.User" resultMap="BaseResultMap">
select <include refid="Base_Column_List" />
from user
<where>
isdelete = 0
<if test="username != null and username!=''">
and username like concat('%',#{username,jdbcType=VARCHAR},'%')
</if>
<if test ="userrole !=null and userrole !=''">
and userrole like concat('%',#{userrole,jdbcType=VARCHAR},'%')
</if>
<if test ="phone !=null and phone !=''">
and phone like concat('%',#{phone,jdbcType=VARCHAR},'%')
</if>
</where>
order by id desc
</select>
<!--根據(jù)id查詢-->
<select id="findUserById" resultType="com.imut.sccos.pojo.User">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
</mapper>啟動(dòng)類:Spring boot項(xiàng)目自帶的啟動(dòng)類,顧名思義就是用來啟動(dòng)項(xiàng)目的。
@SpringBootApplication
@MapperScan("com.imut.sccos.mapper") //掃描mapper包位置
public class SccosApplication {
public static void main(String[] args) {
SpringApplication.run(SccosApplication.class, args);
}
}2.配置類寫法下的CRUD
emmm個(gè)人很不喜歡配置類,寫的東西有點(diǎn)多,不愿意寫,但是這種寫法更容易搞清楚類與類之間的關(guān)系。了解即可。
3.使用Mybatis逆向工程生成CRUD
核心工具:Mybatis Generator(代碼生成器)
他能直接把表結(jié)構(gòu)轉(zhuǎn)化為Mapper接口和xml文件,以及給你生成一份實(shí)體類。
導(dǎo)入依賴坐標(biāo):
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>在resources下創(chuàng)建它的配置文件:

導(dǎo)入后找到該文件,復(fù)制它的路徑,在下面的配置文件中需要用到。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<!--導(dǎo)入屬性配置-->
<!-- <properties resource="datasource.properties"></properties>-->
<!--1.修改點(diǎn):指定特定數(shù)據(jù)庫的jdbc驅(qū)動(dòng)jar包的位置,復(fù)制到此處-->
<classPathEntry location="C:\Users\user\.m2\repository\com\mysql\mysql-connector-j\8.0.33\mysql-connector-j-8.0.33.jar"/>
<context id="default" targetRuntime="MyBatis3">
<!-- optional,旨在創(chuàng)建class時(shí),對注釋進(jìn)行控制 -->
<commentGenerator>
<property name="suppressDate" value="true"/>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--2.修改點(diǎn):jdbc的數(shù)據(jù)庫連接 -->
<jdbcConnection
driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/ld_mysql0317? characterEncoding=utf8 & useSSL=false & serverTimezone=UTC & rewriteBatchedStatements=true"
userId="root"
password="123456">
</jdbcConnection>
<!-- 非必需,類型處理器,在數(shù)據(jù)庫類型和java類型之間的轉(zhuǎn)換控制-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- Model模型生成器,用來生成含有主鍵key的類,記錄類 以及查詢Example類
targetPackage 指定生成的model生成所在的包名
targetProject 指定在該項(xiàng)目下所在的路徑
-->
<!--3.修改點(diǎn):targetPackage:存儲(chǔ)路徑,修改這個(gè)即可<javaModelGenerator targetPackage="com.mmall.pojo" targetProject=".\src\main\java">-->
<javaModelGenerator targetPackage="com.candy.bean" targetProject="./src/main/java">
<!-- 是否允許子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="false"/>
<!-- 是否對model添加 構(gòu)造函數(shù) -->
<property name="constructorBased" value="true"/>
<!-- 是否對類CHAR類型的列的數(shù)據(jù)進(jìn)行trim操作 -->
<property name="trimStrings" value="true"/>
<!-- 建立的Model對象是否 不可改變 即生成的Model對象不會(huì)有 setter方法,只有構(gòu)造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!--4.修改點(diǎn):mapper映射文件生成所在的目錄 為每一個(gè)數(shù)據(jù)庫的表生成對應(yīng)的SqlMap文件 -->
<!--<sqlMapGenerator targetPackage="mappers" targetProject=".\src\main\resources">-->
<sqlMapGenerator targetPackage="mapper" targetProject="./src/main/resources">
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- 客戶端代碼,生成易于使用的針對Model對象和XML配置文件 的代碼
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper對象
type="MIXEDMAPPER",生成基于注解的Java Model 和相應(yīng)的Mapper對象
type="XMLMAPPER",生成SQLMap XML文件和獨(dú)立的Mapper接口
-->
<!-- 5:修改點(diǎn):targetPackage:mapper接口dao生成的位置 -->
<!--<javaClientGenerator type="XMLMAPPER" targetPackage="com.mmall.dao" targetProject=".\src\main\java">-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.candy.dao" targetProject="./src/main/java">
<!-- enableSubPackages:是否讓schema作為包的后綴 -->
<property name="enableSubPackages" value="false" />
</javaClientGenerator>
<!-- <table tableName="mmall_shipping" domainObjectName="Shipping" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>-->
<!-- <table tableName="mmall_cart" domainObjectName="Cart" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>-->
<!-- <table tableName="mmall_cart_item" domainObjectName="CartItem" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>-->
<!-- <table tableName="mmall_category" domainObjectName="Category" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>-->
<!-- <table tableName="mmall_order" domainObjectName="Order" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>-->
<!-- <table tableName="mmall_order_item" domainObjectName="OrderItem" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>-->
<!-- <table tableName="mmall_pay_info" domainObjectName="PayInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>-->
<!-- <table tableName="mmall_product" domainObjectName="Product" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">-->
<!-- <!– 數(shù)據(jù)庫的表中這兩個(gè)字段用的text,mybatis不同版本生成的不一樣,所以改為VARCHAR –>-->
<!-- <columnOverride column="detail" jdbcType="VARCHAR" />-->
<!-- <columnOverride column="sub_images" jdbcType="VARCHAR" />-->
<!-- </table>-->
<!--6.修改點(diǎn):tableName:你要對數(shù)據(jù)庫中哪張表進(jìn)行生成 domainObjectName:你要生成的對象叫什么名字-->
<table tableName="userinfo" domainObjectName="UserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
<table tableName="userinfo" domainObjectName="UserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
<table tableName="userinfo" domainObjectName="UserInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
<!-- geelynote mybatis插件的搭建 -->
</context>
</generatorConfiguration>注:看注釋修改你的代碼配置,不能直接拿來用
配置完畢后在Maven中點(diǎn)擊該插件即可自動(dòng)生成了:

4.使用Mybatis-plus代碼生成器
官方網(wǎng)站:簡介 | MyBatis-Plus
AutoGenerator 是 MyBatis-Plus 的代碼生成器,通過 AutoGenerator 可以快速生成 Entity、Mapper、Mapper XML、Service、Controller 等各個(gè)模塊的代碼,極大的提升了開發(fā)效率。
引入依賴:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version> <!-- 請根據(jù)需要選擇合適的版本 -->
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.16</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>application.properties:配置數(shù)據(jù)庫文件:
spring.application.name=自己的項(xiàng)目名字 server.port=8086 # MyBatis Plus Configuration spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/ld_mysql0317?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC spring.datasource.username=root spring.datasource.password=123456
添加mapper掃描器:
@SpringBootApplication
@MapperScan("com.candy.dao") //<-----
public class NgdSpringbootMybatisPlus20250820Application {
public static void main(String[] args) {
SpringApplication.run(NgdSpringbootMybatisPlus20250820Application.class, args);
}
}實(shí)體類:自己寫一個(gè)實(shí)體類,具體寫法上面有講,可自己選擇用不用lombok
mapper層:添加一個(gè)接口:
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.candy.bean.Userinfo;
public interface UserinfoMapper extends BaseMapper<Userinfo> {
}然后就沒有然后了,你可以在測試類測試是否成功添加:
@SpringBootTest
class NgdSpringbootMybatisPlus20250820ApplicationTests {
@Autowired
UserInfoMapper userInfoMapper;
@Test
void contextLoads() {
List<UserInfo> userInfos=userInfoMapper.selectList(null);
for (UserInfo userInfo : userInfos) {
System.out.println(userInfo);
}
}
}注:實(shí)體類報(bào)錯(cuò)就不要用lombok了,老實(shí)自己寫方法。
5.B站大佬的寫法
【B站講的最好的SpringBoot教程,一小時(shí)學(xué)會(huì)springboot快速上手+實(shí)戰(zhàn)項(xiàng)目,讓你少走99%彎路!】 https://www.bilibili.com/video/BV1fmvkeeEth/?share_source=copy_web&vd_source=3c83936ad44c69171f2fe73f94be606b
寫法很專業(yè),其中在mapper的實(shí)現(xiàn)里,一個(gè)接口上的繼承實(shí)現(xiàn)CRUD,也很方便:

目前個(gè)人知道的就這些,有新技術(shù)在更
到此這篇關(guān)于Java:CRUD的快速實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Java CRUD實(shí)現(xiàn)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一個(gè)簡單的java學(xué)生寢室查詢系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了一個(gè)簡單的java學(xué)生寢室查詢系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
用Spring Native將SpringBoot程序轉(zhuǎn)換為GraalVM
這篇文章主要介紹了用Spring Native將SpringBoot程序轉(zhuǎn)換為GraalVM的方法,幫助大家更好的理解和學(xué)習(xí)使用SpringBoot,感興趣的朋友可以了解下2021-04-04
Spring ApplicationContext接口功能詳細(xì)介紹
ApplicationContext是Spring應(yīng)用程序中的中央接口,由于繼承了多個(gè)組件,使得ApplicationContext擁有了許多Spring的核心功能,如獲取bean組件,注冊監(jiān)聽事件,加載資源文件等2023-02-02
解決升級JDK報(bào)錯(cuò):module java.base does not“opens&nbs
Spring Boot啟動(dòng)錯(cuò)誤源于Java 9+的JPMS強(qiáng)封裝機(jī)制,反射訪問受限導(dǎo)致異常,解決方案為添加JVM參數(shù)(如--add-opens),繞過模塊訪問限制2025-08-08
springboot中@component注解的使用實(shí)例
這篇文章主要介紹了springboot中@component注解的使用實(shí)例,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
解決Java中SimpleDateFormat線程不安全的五種方案
SimpleDateFormat 就是一個(gè)典型的線程不安全事例,本文主要介紹了解決Java中SimpleDateFormat線程不安全的五種方案,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05
SpringBoot開發(fā)存儲(chǔ)服務(wù)器實(shí)現(xiàn)過程詳解
這篇文章主要為大家介紹了SpringBoot開發(fā)存儲(chǔ)服務(wù)器實(shí)現(xiàn)過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12

