一、添加jpa依赖
<!-- jpa依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
二、建立application.properties文件,配置数据源
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
三、新建实体类
@Entity(name = "chinese")
public class ChineseEntity {
@Id
@Column
private int id;
@Column
private int score;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}
四、新建dao接口
@Repository
public interface ChineseDao extends JpaRepository<ChineseEntity, Integer> {
}
注:必须继承JpaRepository<ChineseEntity, Integer>,Integer代表表的主键的类型
五、新建controller
@RestController
public class JpaController {
@Autowired
private ChineseDao chineseDao;
@ResponseBody
@RequestMapping("/jpa")
public ChineseEntity getChineseEntityById(Integer id){
return chineseDao.findOne(id);
}
}
六、编写主函数运行类,添加如下注解扫包:
@EnableJpaRepositories(basePackages="com.wcj.dao")
@EntityScan("com.wcj.entity")
七、运行如图: