1剪菱、引入pom依賴(lài)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
2罢洲、定義實(shí)體類(lèi)宾肺,與數(shù)據(jù)庫(kù)里的表對(duì)應(yīng):
實(shí)體類(lèi):
@Entity(name = "user")
@Table(name = "t_user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "user_name")
private String userName;
private Integer sex;
private String note;
// getter() and setter()...
}
數(shù)據(jù)庫(kù)表:
注釋?zhuān)?/p>
- @Table指定對(duì)應(yīng)數(shù)據(jù)庫(kù)的表名
- @Id表示該屬性為數(shù)據(jù)表主鍵
- @GeneratedValue表示生成主鍵的策略,這里依賴(lài)數(shù)據(jù)庫(kù)遞增策略
- @Column標(biāo)注屬性名與數(shù)據(jù)庫(kù)的字段名對(duì)應(yīng)贷腕。
3背镇、定義JPA接口
@Repository
public interface JpaUserRepository extends JpaRepository<User, Long> {
}
該接口不需要實(shí)現(xiàn)類(lèi)咬展,Spring會(huì)根據(jù)JPA接口規(guī)范幫我們實(shí)現(xiàn)。
4瞒斩、定義Controller
@Controller
@RequestMapping(value = "/")
@Slf4j
public class UserController {
@Autowired
private JpaUserRepository jpaUserRepository;
@GetMapping("/getUser")
public Object findUserById(Long id) {
return jpaUserRepository.findById(id).get();
}
}
5挚赊、向SpringBoot指定掃描接口和實(shí)體類(lèi)路徑
@SpringBootApplication
@EnableJpaRepositories("com.example.demo.dao")
@EntityScan("com.example.demo.entity")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
啟動(dòng)項(xiàng)目,訪(fǎng)問(wèn)controller對(duì)應(yīng)的接口济瓢,即可得到從數(shù)據(jù)庫(kù)讀取的User值荠割。