如何在Spring Boot中配置和使用数据库
在Spring Boot中,配置和使用数据库非常简单,通常通过以下步骤完成:
添加依赖
在pom.xml中添加所需的数据库依赖。例如,使用MySQL数据库:
xml
复制
配置数据源
在application.properties或application.yml中配置数据库连接信息:
properties
复制
spring.datasource.url=jdbc:mysql://localhost:3306/your_database_name
spring.datasource.username=root
spring.datasource.password=your_password
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
使用JPA或MyBatis
JPA(推荐):添加JPA依赖并定义实体类和Repository。
xml
复制
定义实体类:
java
复制
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private int age;
}
定义Repository:
java
复制
public interface UserRepository extends JpaRepository<User, Long> {
}
MyBatis:添加MyBatis依赖并配置Mapper。
xml
复制
定义Mapper接口:
java
复制
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User getUserById(Long id);
}
使用数据源
在Service层或Controller中注入Repository或Mapper,使用数据库操作。
java
复制
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix