Spring Boot 数据库操作
数据源配置
-
Oracle 数据源配置
-
MySQL 数据源配置
-
在pom中添加依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency>
-
在配置文件中添加如下配置
spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.url=jdbc:mysql://127.0.0.1:3306/mysql spring.datasource.username=用户名 spring.datasource.password=密码 # [create|create-drop|update|validate] spring.jpa.hibernate.ddl-auto=update
-
数据库操作
-
添加实体类
@Entity @Table(name = "OMS_USER") public class OmsUser implements Serializable { private static final long serialVersionUID = 1L; @Id private String id; @Column(name = "DISPLAY_ID") private String displayId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getDisplayId() { return displayId; } public void setDisplayId(String displayId) { this.displayId = displayId; } }
PS:
Entity
中不映射成列的字段,使用@Transient
注解。 -
添加DAO
继承
JpaRepository
类即可(已封装简单的CRUD操作)。public interface OmsUserRepository extends JpaRepository<OmsUser, String> { }
-
测试
@RestController @RequestMapping(value = "/api") public class StudentController { @Autowired OmsUserRepository omsUserRepository; @GetMapping(value = "/user") public List<OmsUser> getAllUser() { return this.omsUserRepository.findAll(); } @GetMapping(value = "/user/{id}") public OmsUser getUserById(@PathVariable("id") String id) { return omsUserRepository.findById(id).get(); } }