1、pom.xml新添加依赖包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
2、在application.properties 文件中配置连接参数:
spring.datasource.url=jdbc:oracle:thin:@localhost:1521:orcl spring.datasource.username=userstudy spring.datasource.password=userstudy spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver spring.jpa.properties.hibernate.hbm2ddl.auto=update
3、创建实体类Teacher,由于配置了hibernate.hbm2ddl.auto
,在应用启动的时候框架会自动去数据库中创建对应的表。
@Entity public class Teacher { @Id @GeneratedValue private Long id; @Column(nullable = false) private String name;
@Column(nullable = false) private Integer age; public Teacher() { } public Teacher(String name, Integer age) { this.name = name; this.age = age; } //get set 方法 }
4、创建Teacher的数据访问接口:
public interface TeacherRepository extends JpaRepository<Teacher, Long> { Teacher findByName(String name); Teacher findByNameAndAge(String name, Integer age); Teacher save(Teacher teacher); }
5、新建Controller类:
@RestController @RequestMapping(value="/Teacher") public class TeacherController { @Autowired private TeacherRepository teacherRepository; @RequestMapping(value="/findByName") public Teacher findByName(String name){ Teacher teacher=teacherRepository.findByName(name); return teacher; } @RequestMapping(value="/findAll") public List<Teacher> findAll(){ List<Teacher> teacher=teacherRepository.findAll(); return teacher; } }
6、启动项目后测试: