赞
踩
时间关系,不做太多解释,sqlite 是一个很轻量级的数据库,可以满足日常 sql 的需求,如果不需要使用像 mysql 那样重量级的数据库可以考虑使用 sqllite。我用的 SQLite 必须使用一个缓存文件,例如:jdbc:sqlite:D:/program/sqlite3/db/pro.db,如果你们有纯内存配置方式(无 db 配置文件)可以分享给我,谢谢。
SQLite 一般用于处理小到中型数据存储,对于高并发高流量的应用不适用。
<?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.example</groupId> <artifactId>springboot-learning-parents</artifactId> <version>1.0-SNAPSHOT</version> </parent> <groupId>springboot-demo</groupId> <artifactId>springboot-sqlite</artifactId> <version>1.0-SNAPSHOT</version> <name>springboot-sqlite</name> <description>springboot集成sqlite</description> <properties> <start-class>com.demo.SpringbootSqliteApplication</start-class> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <mybatisplus.version>3.5.1</mybatisplus.version> <freemaker.version>2.3.31</freemaker.version> <mysql.version>8.0.28</mysql.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!-- mybatis-plus 所需依赖 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatisplus.version}</version> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> <version>${mybatisplus.version}</version> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.31</version> </dependency> <!-- sqlite 依赖包 --> <dependency> <groupId>org.xerial</groupId> <artifactId>sqlite-jdbc</artifactId> <version>3.36.0.3</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
#端口,项目上下文 server: port: 8080 servlet: context-path: /springboot-sqlite spring: datasource: username: leo825 password: 1WSX@357wj url: jdbc:sqlite:D:/program/sqlite3/db/pro.db driver-class-name: org.sqlite.JDBC # 初始化表 schema: classpath:schema.sql # 初始化数据 data: classpath:data.sql initialization-mode: always continue-on-error: true # mybatis-plus 配置 mybatis-plus: mapper-locations: classpath*:/mapper/**/*.xml #实体扫描,多个package用逗号或者分号分隔 typeAliasesPackage: com.dmo.entity global-config: #数据库相关配置 db-config: #主键类型 AUTO:"数据库ID自增", INPUT:"用户输入ID", ID_WORKER:"全局唯一ID (数字类型唯一ID)", UUID:"全局唯一ID UUID"; id-type: AUTO #字段策略 IGNORED:"忽略判断",NOT_NULL:"非 NULL 判断"),NOT_EMPTY:"非空判断" field-strategy: NOT_NULL #驼峰下划线转换 column-underline: true logic-delete-value: -1 logic-not-delete-value: 0 banner: false #原生配置 configuration: # 打印sql log-impl: org.apache.ibatis.logging.stdout.StdOutImpl map-underscore-to-camel-case: true cache-enabled: false call-setters-on-nulls: true jdbc-type-for-null: 'null' # 日志输出配置 logging: level: root: INFO org: springframework: security: WARN web: ERROR file: path: ./logs name: './logs/sqlite-demo.log' pattern: file: '%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n' console: '%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}:%L - %msg%n'
create table if not exists t_user (
`id` int primary key not null ,
`username` char (50) not null,
`pwd` char(50) not null,
`create_time` datetime not null,
`update_time` datetime
) ;
insert into t_user(id, username, pwd, create_time, update_time) values (0,'zhhangsan','1222', datetime('now', 'localtime'), datetime('now', 'localtime'))
Result.java
package com.demo.base; public class Result<T> { private Integer code; private String msg; private String message; private T data; public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data; } public void setData(T data) { this.data = data; } public Result ok(T t){ this.setCode(1000); this.setMsg("成功"); this.setMessage("成功"); this.setData(t); return this; } public Result fail(String msg){ this.setCode(1001); this.setMsg(msg); this.setMessage(msg); return this; } public Result() { } public Result(Integer code, String msg) { this.code = code; this.msg = msg; this.setMessage(msg); } public Result(Integer code, String msg, T data) { this.code = code; this.msg = msg; this.data = data; this.setMessage(msg); } }
User.java
package com.demo.entity; import com.baomidou.mybatisplus.annotation.*; import com.fasterxml.jackson.annotation.JsonFormat; import java.io.Serializable; import java.util.Date; /** * <p> * 用户表 * </p> * * @author Leo825 * @since 2022-07-05 */ @TableName("t_user") public class User implements Serializable { private static final long serialVersionUID = 1L; /** * 用户主键 */ @TableId(value = "id", type = IdType.AUTO) private Integer id; /** * 用户名称 */ private String username; /** * 密码 */ private String pwd; /** * 创建时间,MyMetaObjectHandler 配合使用,入库的时候自动填充 */ @TableField(value = "create_time", fill = FieldFill.INSERT) @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date createTime; /** * 修改时间,MyMetaObjectHandler 配合使用,入库的时候自动填充 */ @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE) @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date updateTime; 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 getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } @Override public String toString() { return "User{" + "id=" + id + ", username=" + username + ", pwd=" + pwd + ", createTime=" + createTime + ", updateTime=" + updateTime + "}"; } }
package com.demo.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.demo.entity.User; /** * <p> * 用户表 Mapper 接口 * </p> * * @author Leo825 * @since 2022-07-05 */ public interface UserMapper extends BaseMapper<User> { }
package com.demo.service; import com.demo.entity.User; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 用户表 服务类 * </p> * * @author Leo825 * @since 2022-07-05 */ public interface IUserService extends IService<User> { }
impl 实现类:
package com.demo.service.impl; import com.demo.entity.User; import com.demo.mapper.UserMapper; import com.demo.service.IUserService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 用户表 服务实现类 * </p> * * @author Leo825 * @since 2022-07-05 */ @Service public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService { }
MybatisPlusConfig.java
package com.demo.config; import com.baomidou.mybatisplus.annotation.DbType; import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * mybatisplus 配置 */ @Configuration public class MybatisPlusConfig { /** * 老版本,目前已失效 * @return */ /**@Bean public PaginationInterceptor paginationInterceptor() { PaginationInterceptor paginationInterceptor = new PaginationInterceptor(); return paginationInterceptor; }*/ /** * 新的分页插件,一缓和二缓遵循mybatis的规则, */ @Bean public MybatisPlusInterceptor mybatisPlusInterceptor() { MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.SQLITE)); return interceptor; } }
MyMetaObjectHandler.java
package com.demo.config; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; import java.util.Date; /** * 填充公共字段 * */ @Slf4j @Component public class MyMetaObjectHandler implements MetaObjectHandler { @Override public void insertFill(MetaObject metaObject) { log.info("start insert fill..."); this.setFieldValByName("createTime", new Date(), metaObject); this.setFieldValByName("updateTime", new Date(), metaObject); } @Override public void updateFill(MetaObject metaObject) { log.info("start update fill..."); this.setFieldValByName("updateTime", new Date(), metaObject); } }
package com.demo.controller; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.demo.base.Result; import com.demo.entity.User; import com.demo.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; 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; /** * controller 测试 * */ @RestController @RequestMapping("/user") public class UserController { /** * 构造方法注入 */ @Autowired IUserService userService; /** * 保存数据 * * @return */ @GetMapping("/save") public Result save() { User user = new User(); user.setId(10); user.setUsername("miaolinlin"); user.setPwd("121212"); userService.save(user); return new Result().ok(user); } /** * 修改数据 * * @param id * @return */ @GetMapping("/update") public Result update(Integer id) { User user = new User(); user.setId(id); user.setPwd("1111111111"); userService.updateById(user); return new Result().ok("{}"); } @GetMapping("/list") public Result list() { // 返回所有 List<User> list = userService.list(); return new Result().ok(list); } @GetMapping("/listByContion") public Result listByContion() { /** * 条件查询, 通过QueryWrapper来实现查询的条件: * eq: 代表相等 * like: 模糊匹配 * orderBy: 排序 * in, notin * 大于,小于,between等 */ List<User> list = userService.list(new LambdaQueryWrapper<User>() // 查询年龄=11的 .eq(User::getUsername, "miao") // 模糊匹配 .like(User::getPwd, "%111%") // 排序,按照创建时间 .orderByDesc(User::getCreateTime) ); return new Result().ok(list); } /** * 根据id获取数据 * * @param id * @return */ @GetMapping("/getById") public Result getById(Integer id) { User user = userService.getById(id); return new Result().ok(user); } /** * 删除数据 * * @param id * @return */ @GetMapping("/delete") public Result delete(Integer id) { userService.removeById(id); return new Result().ok("success"); } /** * 分页查询 * * @param pageNum * @param pageSize * @param name * @return */ @GetMapping("/page") public Result page(int pageNum, int pageSize, String name) { IPage<User> page = new Page<>(pageNum, pageSize); IPage<User> page1 = userService.page(page, new LambdaQueryWrapper<User>() // 主要演示这里可以加条件。在name不为空的时候执行 .like(StringUtils.isNotEmpty(name), User::getUsername, "%" + name + "%")); return new Result().ok(page1); } }
package com.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(value = "com.demo.mapper")
public class SpringbootSqliteApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootSqliteApplication.class, args);
}
}
springboot 整合 sqllite 和 mysql 差不多,代码库地址如下:
https://gitee.com/leo825/springboot-learning-parents.git
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。