ideaJAVA数据库增删查改完整代码
时间: 2024-12-25 18:08:10 浏览: 13
在IntelliJ IDEA中编写Java代码连接数据库并完成基本的增删查改操作,通常会涉及使用Java Persistence API (JPA) 或 JDBC (Java Database Connectivity)。以下是使用JPA的一个简单示例:
首先,确保已经添加了JPA依赖(如果你使用Maven或Gradle):
```xml
<!-- Maven -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
// Gradle
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
```
然后创建一个实体类(如User.java):
```java
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// getters and setters
}
```
配置数据源和JPA:
```java
@Configuration
@EnableJpaRepositories(basePackages = "com.example.demo.repository")
@EntityScan("com.example.demo.entity") // 扫描entity包
public class JpaConfig {
@Value("${spring.datasource.url}")
private String url;
@Value("${spring.datasource.username}")
private String username;
@Value("${spring.datasource.password}")
private String password;
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); // 替换为实际驱动
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
@Bean
public PlatformTransactionManager transactionManager(DataSource dataSource) {
return new JpaTransactionManager(entityManagerFactory());
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource());
factory.packaged扫面策略改为"com.example.demo.entity"; // 替换为实际的包名
factory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
factory.setJpaProperties(hibernateProperties());
return factory;
}
private Map<String, Object> hibernateProperties() {
Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
properties.put("hibernate.show_sql", true); // 开启调试模式打印SQL
return properties;
}
}
```
最后,在Repository接口和Service层实现CRUD操作(假设UserRepository.java和UserService.java):
```java
// UserRepository.java
public interface UserRepository extends JpaRepository<User, Long> {
}
// UserService.java
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User createUser(User user) {
return userRepository.save(user);
}
public Optional<User> getUser(Long id) {
return userRepository.findById(id);
}
public void updateUser(User user) {
userRepository.save(user);
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
}
```
为了测试这些操作,你可以创建一个Controller层(如UserController.java):
```java
@RestController
@RequestMapping("/users")
public class UserController {
private final UserService userService;
public UserController(UserService userService) {
this.userService = userService;
}
// ... 添加对应HTTP映射的方法,例如 POST、GET、PUT 和 DELETE 请求
}
```
这只是一个简单的例子,实际应用中可能需要处理事务、错误处理和其他细节。
阅读全文