網(wǎng)站優(yōu)化與seo市場(chǎng)推廣方案和思路
1、Mybatis Plus介紹
Mybatis,用過的都知道,這里不介紹,mybatis plus只是在mybatis原來的基礎(chǔ)上做了些改進(jìn),增強(qiáng)了些功能,增強(qiáng)的功能主要為增加更多常用接口方法調(diào)用,減少xml內(nèi)sql語句編寫,也可以自定義接口,簡單的查詢、新增和刪除只需調(diào)用內(nèi)置接口方法即可,有點(diǎn)類似于springdata jpa的方式。
2、插件引入和啟動(dòng)配置
2.1、pom.xml
<dependencies>
<!-- mybatis-plus插的springboot支持 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.2</version></dependency><!-- MySql --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.30</version></dependency><!-- 連接池 --><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.2.15</version></dependency>
</dependencies>
2.2、application.yml配置
server:port: 8080
spring:application:name: mybatisPlusdatasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://127.0.0.1:3306/mybatistest?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true&useSSL=falseusername: liuliupassword: 123456
mybatis:database:type: mysql
mybatis-plus:mapper-locations: classpath*:mapper/*.xml
mapper-locations: 這里配置xxxMapper.xml文件路徑的地方,靜態(tài)目錄【resources】下,如果項(xiàng)目簡單,不需要用到xml內(nèi)的查詢,這里可以省略掉。
2.3、啟動(dòng)入口配置
package com.liuliu.demo;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
//啟動(dòng)前需掃描dao接口文件所對(duì)應(yīng)的包路徑,加入到bean處理,
//這里很重要,否則自定義的查詢接口無效
@MapperScan("com.liuliu.demo.mapper")
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}}
3、查詢
3.1、創(chuàng)建數(shù)據(jù)表對(duì)象
數(shù)據(jù)表結(jié)構(gòu):
CREATE TABLE `tb_user` (`id` int(11) NOT NULL AUTO_INCREMENT,`user_name` varchar(32) NOT NULL COMMENT '用戶名稱',`password` varchar(32) DEFAULT NULL COMMENT '密碼',`name` varchar(64) DEFAULT NULL COMMENT 'name',`age` int(11) DEFAULT NULL,`email` varchar(32) DEFAULT NULL,`demp_id` int(11) DEFAULT NULL,`md5` char(32) DEFAULT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `demp` (`id` int(11) NOT NULL AUTO_INCREMENT,`classname` varchar(32) NOT NULL,PRIMARY KEY (`id`),UNIQUE KEY `actable_uni_classname` (`classname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
創(chuàng)建實(shí)體類:
@Data
@TableName("tb_user")
public class User {@TableId(type = IdType.AUTO)private Integer id;private String userName;@TableField(select = false)private String password;private String name;private Integer age;@TableField(value = "email")private String mail;@TableField(exist = false)private String address;@TableField(value = "demp_id")private Integer dempId;private String md5;@TableField(exist = false)private Demp demp;
}
@Data
public class Demp {@TableId(type = IdType.AUTO)private Integer id;private String classname;
}
創(chuàng)建mapperDao接口
@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {
}
@Mapper
@Repository
public interface DempMapper extends BaseMapper<Demp> {
}
創(chuàng)建service接口
package com.liuliu.demo.service;public interface UserService extends IService<User> {
}
這里只需演示一個(gè)表的查詢,其它的service就不演示創(chuàng)建了。
3.2、查詢數(shù)據(jù)
先手動(dòng)創(chuàng)建好數(shù)據(jù):
創(chuàng)建一個(gè)實(shí)現(xiàn)查詢接口service類
package com.liuliu.demo.service.impl;@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {@Autowiredprivate UserMapper userMapper;public void findUserModule(){//查多條,當(dāng)沒查到時(shí)返回[]System.out.println(list(query().ge("id", 2).getWrapper()));//只查一條,當(dāng)沒查到時(shí)返回nullSystem.out.println(getOne(query().ge("age", 22).orderByDesc("id").getWrapper().last("limit 1")));}
創(chuàng)建一個(gè)controller類
@RestController
public class UserController {@Autowiredprivate UserServiceImpl userserviceimpl;@GetMapping("findtest")public long findtestmodule(){userserviceimpl.findUserModule();//作為測(cè)試效果,這里不做數(shù)據(jù)返回了,而是在內(nèi)部控制臺(tái)打印return System.currentTimeMillis();}
}
控制臺(tái)輸出的結(jié)果:
[User(id=2, userName=李四, password=null, name=lisi, age=22, mail=lisi@aa.com, address=null, dempId=2, md5=null, demp=null), User(id=3, userName=王強(qiáng), password=null, name=wangqiang, age=35, mail=wang@qq.com, address=null, dempId=1, md5=null, demp=null), User(id=5, userName=川建國, password=null, name=DonaldTrump, age=83, mail=donald@qq.com, address=null, dempId=2, md5=null, demp=null)]
User(id=5, userName=川建國, password=null, name=DonaldTrump, age=83, mail=donald@qq.com, address=null, dempId=2, md5=null, demp=null)
是不是很解單?新增和刪除數(shù)據(jù)方法自己去試試:
this.save(user);
userMapper.deleteById(id);
3.3、關(guān)聯(lián)查詢
通過Mybatis plus自帶方法來查關(guān)聯(lián)表,暫時(shí)好像還不支持,但可以使用xml文件內(nèi)的sql語法來創(chuàng)建
3.3.1、自定義接口方法
package com.liuliu.demo.mapper;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.liuliu.demo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;import java.util.List;@Mapper
@Repository
public interface UserMapper extends BaseMapper<User> {User getUserById(Integer id);List<User> getUserAll();
}
3.3.2、創(chuàng)建userMapper.xml
路徑:resources/mapper/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.liuliu.demo.mapper.UserMapper"><sql id="fieldAll">tb_user.*,demp.id as dempId,demp.classname</sql><resultMap id="userMap" type="com.liuliu.demo.pojo.User"><id property="id" column="id" /><result property="userName" column="user_name" /><result property="name" column="name" /><result property="age" column="age" /><result property="password" column="password" /><result property="mail" column="email" /><result property="dempId" column="demp_id" /><association property="demp" javaType="com.liuliu.demo.pojo.Demp"><result property="id" column="dempId" /><result property="classname" column="classname" /></association></resultMap><select id="getUserById" resultMap="userMap" parameterType="Integer">select <include refid="fieldAll"/> from tb_user join demp on tb_user.demp_id=demp.id where tb_user.id=#{id}</select><select id="getUserAll" resultMap="userMap">select <include refid="fieldAll"/> from tb_user join demp on tb_user.demp_id=demp.id</select>
</mapper>
3.3.3、實(shí)現(xiàn)關(guān)聯(lián)查詢
UserServiceImpl.java內(nèi)添加查詢方法
public User findByid(Integer id){return userMapper.getUserById(id);
}@Override
public List<User> findUserAll() {return userMapper.getUserAll();
}
控制器內(nèi)添加查詢對(duì)接
@GetMapping("/findById")public User findById(@RequestParam(name = "id") Integer id){return userserviceimpl.findByid(id);}@GetMapping("/findUserAll")public List<User> findUserAll(){return userserviceimpl.findUserAll();}
demp表數(shù)據(jù):
訪問結(jié)果
http://127.0.0.1:8080/findById?id=5
{"id": 5,"userName": "川建國","password": "fjiewofdsafadfkewok","name": "DonaldTrump","age": 83,"mail": "donald@qq.com","address": null,"dempId": 2,"md5": null,"demp": {"id": 2,"classname": "技術(shù)部"}
}
http://127.0.0.1:8080/findUserAll
[{"id": 1,"userName": "張三","password": "123456","name": "zhangsan","age": 20,"mail": "da@aa.com","address": null,"dempId": 1,"md5": null,"demp": {"id": 1,"classname": "財(cái)務(wù)部"}},{"id": 2,"userName": "李四","password": "123456","name": "lisi","age": 22,"mail": "lisi@aa.com","address": null,"dempId": 2,"md5": null,"demp": {"id": 2,"classname": "技術(shù)部"}},{"id": 3,"userName": "王強(qiáng)","password": "fjeiwofjdksajl","name": "wangqiang","age": 35,"mail": "wang@qq.com","address": null,"dempId": 1,"md5": null,"demp": {"id": 1,"classname": "財(cái)務(wù)部"}},{"id": 5,"userName": "川建國","password": "fjiewofdsafadfkewok","name": "DonaldTrump","age": 83,"mail": "donald@qq.com","address": null,"dempId": 2,"md5": null,"demp": {"id": 2,"classname": "技術(shù)部"}}
]
4、SpringBoot啟動(dòng)時(shí)自動(dòng)更新數(shù)據(jù)表
自動(dòng)更新表結(jié)構(gòu),在團(tuán)隊(duì)開發(fā)中非常重要,否則在開發(fā)管理上很麻煩,并且增加正式環(huán)境中的運(yùn)維難度,每次新增一個(gè)表或更改一個(gè)表結(jié)構(gòu),都需要單獨(dú)在數(shù)據(jù)庫中去操作,這不符合實(shí)際開發(fā)應(yīng)用。
Mybatis plus自動(dòng)更新數(shù)據(jù)表結(jié)構(gòu)在設(shè)置上相比springdata jpa要復(fù)雜一些,需要先在pom中引入一個(gè)包,然后在yml配置文件中配置相關(guān)啟動(dòng)開關(guān),還需在入口處配置實(shí)體掃描。
4.1、pom.xml引入相關(guān)包
<dependency><groupId>com.gitee.sunchenbin.mybatis.actable</groupId><artifactId>mybatis-enhance-actable</artifactId><version>1.1.1.RELEASE</version>
</dependency>
4.2、application.yml增加內(nèi)容
mybatis:table:auto: update #update: 數(shù)據(jù)表實(shí)體類只要有變動(dòng),就會(huì)對(duì)數(shù)據(jù)表實(shí)施更改操作,包括刪除表、新增表、更新表字段等。model:pack: com.liuliu.demo.pojo #掃描數(shù)據(jù)實(shí)體位置database:type: mysql #數(shù)據(jù)庫類型
mybatis-plus:
#前部分為自動(dòng)更新需用到的查詢xmlmapper-locations: com/gitee/sunchenbin/mybatis/actable/mapping/*/*.xml,classpath*:mapper/*.xml
4.3、入口啟動(dòng)文件配置
package com.liuliu.demo;import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;@SpringBootApplication
@MapperScan({"com.gitee.sunchenbin.mybatis.actable.dao.*", "com.liuliu.demo.mapper"})
@ComponentScan({"com.gitee.sunchenbin.mybatis.actable.manager.*", "com.liuliu.demo.*"})
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
注意@ComponentScan,前段是mybatis自帶的,沒有是會(huì)報(bào)錯(cuò)的,會(huì)報(bào)找不到對(duì)應(yīng)的bean,后段是當(dāng)前項(xiàng)目根目錄包,如果不寫,會(huì)訪問不到任何控制器,因?yàn)檫@里的掃描會(huì)導(dǎo)致后面的been添加無效。
4.4、數(shù)據(jù)實(shí)體配置
實(shí)體類需要添加對(duì)應(yīng)的@注解,否則前面做了那么多,也沒有用。
主要有:
@Table
@IsKey
@IsAutoIncrement
@Column
@Unique
@Index
User.java
package com.liuliu.demo.pojo;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.gitee.sunchenbin.mybatis.actable.annotation.*;
import lombok.Data;@Data
@TableName("tb_user")
@Table(name = "tb_user")
public class User {@TableId(type = IdType.AUTO)@IsKey@IsAutoIncrement@Columnprivate Integer id;//這里有個(gè)bug說明下,這個(gè)length默認(rèn)是255,設(shè)置length時(shí)如果不設(shè)置type,是無效的,最后查看數(shù)據(jù)表結(jié)果還是255@Column(name = "user_name", length = 32, comment = "用戶名稱", type = "varchar", isNull = false)private String userName;@TableField(select = false)@Column(name = "password", length = 32, comment = "密碼", type = "varchar")private String password;@Column(name = "name", length = 64, comment = "name", type = "varchar")private String name;@Columnprivate Integer age;@TableField(value = "email")@Column(name = "email", length = 32, type = "varchar")private String mail;@TableField(exist = false)private String address;@TableField(value = "demp_id")@Column(name = "demp_id")private Integer dempId;@Column(type = "char", length = 32)private String md5;@TableField(exist = false)private Demp demp;
}
Demp.java
package com.liuliu.demo.pojo;import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.gitee.sunchenbin.mybatis.actable.annotation.*;
import lombok.Data;@Data
@Table(name = "demp")
public class Demp {@TableId(type = IdType.AUTO)@Column@IsAutoIncrement@IsKeyprivate Integer id;@Column(type = "varchar", length = 32, isNull = false)@Uniqueprivate String classname;
}
4.5、重啟springboot應(yīng)用查看效果
重啟前先清空數(shù)據(jù)表
:: Spring Boot :: (v2.3.12.RELEASE)2023-07-31 16:49:42.628 INFO 17156 --- [ main] com.liuliu.demo.DemoApplication : Starting DemoApplication on yonnry with PID 17156 (C:\src\test\mybatisPlusDemo\target\classes started by yongp in C:\src\test\mybatisPlusDemo)
2023-07-31 16:49:42.629 INFO 17156 --- [ main] com.liuliu.demo.DemoApplication : No active profile set, falling back to default profiles: default
2023-07-31 16:49:42.669 WARN 17156 --- [kground-preinit] o.s.h.c.j.Jackson2ObjectMapperBuilder : For Jackson Kotlin classes support please add "com.fasterxml.jackson.module:jackson-module-kotlin" to the classpath
2023-07-31 16:49:43.198 INFO 17156 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2023-07-31 16:49:43.203 INFO 17156 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2023-07-31 16:49:43.203 INFO 17156 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.46]
2023-07-31 16:49:43.241 INFO 17156 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2023-07-31 16:49:43.241 INFO 17156 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 575 ms
2023-07-31 16:49:43.422 WARN 17156 --- [ main] c.b.m.core.injector.AbstractMethod : [com.liuliu.demo.mapper.DempMapper.selectById] Has been loaded by XML or SqlProvider or Mybatis's Annotation, so ignoring this injection for [class com.baomidou.mybatisplus.core.injector.methods.SelectById]_ _ |_ _ _|_. ___ _ | _
| | |\/|_)(_| | |_\ |_)||_|_\ / | 3.5.2
2023-07-31 16:49:43.742 INFO 17156 --- [ main] c.g.s.m.a.m.handler.StartUpHandlerImpl : databaseType=mysql,開始執(zhí)行mysql的處理方法
2023-07-31 16:49:43.749 INFO 17156 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-07-31 16:49:43.818 INFO 17156 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
file類型的掃描:com.liuliu.demo.pojo
2023-07-31 16:49:43.907 INFO 17156 --- [ main] s.m.a.m.s.SysMysqlCreateTableManagerImpl : 開始創(chuàng)建表:tb_user
2023-07-31 16:49:43.958 INFO 17156 --- [ main] s.m.a.m.s.SysMysqlCreateTableManagerImpl : 完成創(chuàng)建表:tb_user
2023-07-31 16:49:43.958 INFO 17156 --- [ main] s.m.a.m.s.SysMysqlCreateTableManagerImpl : 開始創(chuàng)建表:demp
2023-07-31 16:49:43.973 INFO 17156 --- [ main] s.m.a.m.s.SysMysqlCreateTableManagerImpl : 完成創(chuàng)建表:demp
2023-07-31 16:49:43.973 INFO 17156 --- [ main] s.m.a.m.s.SysMysqlCreateTableManagerImpl : 開始創(chuàng)建表demp中的唯一約束actable_uni_classname
2023-07-31 16:49:43.982 INFO 17156 --- [ main] s.m.a.m.s.SysMysqlCreateTableManagerImpl : 完成創(chuàng)建表demp中的唯一約束actable_uni_classname
2023-07-31 16:49:44.064 INFO 17156 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2023-07-31 16:49:44.100 INFO 17156 --- [ main] o.s.b.a.w.s.WelcomePageHandlerMapping : Adding welcome page: class path resource [static/index.html]
2023-07-31 16:49:44.154 INFO 17156 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2023-07-31 16:49:44.159 INFO 17156 --- [ main] com.liuliu.demo.DemoApplication : Started DemoApplication in 1.738 seconds (JVM running for 2.192)
注意看,已成功啟動(dòng),console中有提示“完成創(chuàng)建數(shù)據(jù)表***”,修改表就不演示了,原理是一樣的。
5、結(jié)束
源碼下載:https://download.csdn.net/download/u012029030/88136220
感謝觀看,以上是我對(duì)springboot總結(jié)的經(jīng)驗(yàn),如有什么疑問或不同意見,歡迎留言。