,可以通过以下步骤完成:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// 省略构造方法、getter和setter
}
@Component
public class DataInitializer implements CommandLineRunner {
private final UserRepository userRepository;
public DataInitializer(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public void run(String... args) throws Exception {
// 创建一个User对象并保存到数据库
User user = new User();
user.setName("John Doe");
user.setEmail("john.doe@example.com");
userRepository.save(user);
}
}
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.hibernate.ddl-auto=update
这样,就使用MySQL和Java CommandLineRunner成功实现了Spring对象保存的问题。在实际应用中,可以根据需要进行扩展和优化,例如添加数据校验、查询操作等。
领取专属 10元无门槛券
手把手带您无忧上云