(一)连接 Oracle 数据库
在 Java 中,使用 JDBC(Java Database Connectivity)连接 Oracle 数据库是一种常见的方法。以下是一个示例代码展示如何在 Java 中使用 JDBC 连接 Oracle 数据库:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class OracleJDBCConnection {
public static void main(String[] args) {
String url = "jdbc:oracle:thin:@your_host:1521:your_service_name";
String username = "your_username";
String password = "your_password";
try {
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println("Connected to Oracle database successfully!");
connection.close();
} catch (SQLException e) {
e.printStackTrace();
在上述代码中,需要将your_host、your_service_name、your_username和your_password替换为实际的数据库连接信息。
(二)使用 JPA
Java 持久化 API(JPA)提供了一种对象关系映射(ORM)的解决方案,使得在 Java 应用程序中进行数据库操作更加便捷。以下是使用 JPA 操作 Oracle 数据库的方法:
1. 添加依赖
在 Maven 项目中,需要添加 JPA 和 Oracle 数据库驱动的依赖。例如:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.2.0</version>
</dependency>
2. 配置属性
在application.properties文件中配置数据库连接信息和 JPA 属性:
spring.datasource.url=jdbc:oracle:thin:@your_host:1521:your_service_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.jpa.show-sql=true
3. 实体类定义
定义一个实体类,对应数据库中的表:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
private String name;
private int age;
// Getters and setters
}
4. 仓库接口
创建一个仓库接口,继承自 JpaRepository,以便进行数据库操作:
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
}
5. 服务类和控制器
可以创建一个服务类来封装业务逻辑,并在控制器中调用服务类的方法进行数据库操作。例如:
import org.springframework.stereotype.Service;
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User saveUser(User user) {
return userRepository.save(user);
}
}
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.saveUser(user);
}
}
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_56693899/article/details/143579451