为了搭建一个Spring Boot项目来连接Oracle数据库,你需要以下步骤和代码示例。以下是各个层次的简单实现。
1. **实体类(Entity)** - 这是代表数据库表中一条记录的类。
```java
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "YOUR_TABLE_NAME")
public class YourEntity {
@Id
private Long id;
private String columnName;
// Getters and Setters
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getColumnName() {
return columnName;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
}
```
2. **Mapper层(Repository)** - 这是用于访问数据库的接口。
```java
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface YourEntityRepository extends JpaRepository
{
// Custom query methods if needed
}
```
3. **Service层** - 这是业务逻辑层,用于处理具体业务。
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class YourEntityService {
@Autowired
private YourEntityRepository repository;
public List findAll() {
return repository.findAll();
}
public YourEntity findById(Long id) {
return repository.findById(id).orElse(null);
}
public YourEntity save(YourEntity entity) {
return repository.save(entity);
}
public void deleteById(Long id) {
repository.deleteById(id);
}
}
```
4. **Controller层** - 这是与前端交互的层,用于接收请求和处理响应。
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/your-entity")
public class YourEntityController {
@Autowired
private YourEntityService service;
@GetMapping
public ResponseEntity> getAll() {
return ResponseEntity.ok(service.findAll());
}
@GetMapping("/{id}")
public ResponseEntity getById(@PathVariable Long id) {
YourEntity entity = service.findById(id);
if (entity == null) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok(entity);
}
@PostMapping
public ResponseEntity create(@RequestBody YourEntity entity) {
YourEntity newEntity = service.save(entity);
return ResponseEntity.ok(newEntity);
}
@DeleteMapping("/{id}")
public ResponseEntity deleteById(@PathVariable Long id) {
service.deleteById(id);
return ResponseEntity.ok().build();
}
}
```
此外,你需要在`application.properties`文件中配置Oracle数据库的连接信息:
```properties
spring.datasource.url=jdbc:oracle:thin:@//host:port/dbname
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect
spring.jpa.hibernate.ddl-auto=update
```
确保你有Oracle的JDBC驱动在项目的依赖中,如果是Maven项目,你需要在`pom.xml`中添加以下依赖:
```xml
com.oracle.database.jdbc
ojdbc8
19.8.0.0
```
请根据实际情况调整以上代码中的类名、方法名、变量名等。