springboot使用sqlite
时间: 2023-11-20 14:57:42 浏览: 85
Spring_boot_mybatis_sqlite.zip
以下是使用Spring Boot和SQLite3的示例代码:
1.在pom.xml中添加相关依赖
```xml
<!-- sqlite -->
<dependency>
<groupId>org.xerial</groupId>
<artifactId>sqlite-jdbc</artifactId>
<version>3.21.0.1</version>
</dependency>
<!-- mybatis -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
```
2.在application.properties中配置SQLite3数据库
```properties
spring.datasource.driver-class-name=org.sqlite.JDBC
spring.datasource.url=jdbc:sqlite:/path/to/your/db/file.db
spring.datasource.username=
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.SQLiteDialect
```
3.创建SQLite3数据库表
```sql
CREATE TABLE user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name VARCHAR(50) NOT NULL,
age INTEGER NOT NULL
);
```
4.创建实体类和Mapper接口
User.java
```java
public class User {
private Long id;
private String name;
private Integer age;
// 省略getter和setter
}
```
UserMapper.java
```java
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(@Param("id") Long id);
@Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
void insert(User user);
@Update("UPDATE user SET name=#{name}, age=#{age} WHERE id=#{id}")
void update(User user);
@Delete("DELETE FROM user WHERE id=#{id}")
void delete(Long id);
}
```
5.创建Service类
UserService.java
```java
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findById(Long id) {
return userMapper.findById(id);
}
public void insert(User user) {
userMapper.insert(user);
}
public void update(User user) {
userMapper.update(user);
}
public void delete(Long id) {
userMapper.delete(id);
}
}
```
6.创建Controller类
UserController.java
```java
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{id}")
public User findById(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping("/")
public void insert(@RequestBody User user) {
userService.insert(user);
}
@PutMapping("/")
public void update(@RequestBody User user) {
userService.update(user);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
userService.delete(id);
}
}
```
阅读全文