SpringBoot整合JPA
JPA全称为JPA Persistence API,它是一个数据持久化的类和方法的集合。JPA的目标是制定一个由很多数据库供应商实现的API,开发人员可以通过实现编码实现该API。目前,在Java项目中,在Hibernate实现的JPA是最好的。(案例使用Mysql5.7,在IDEA中实验)
①、自动配置和起步依赖。
②、配置数据源
查看自己的pom.xml
在工程的配置文件applocation.properties(或者application.yml)中配置向相应的选项,这个工程涉及配置两个选项:DataSource数据源配置和JPA的配置。
③、创建实体对象
package com.example.demo.entity;
import javax.persistence.*;
@Entity
public class User {
//Id注解表明该变量对应与数据库
@Id
//GeneratedValue注解设置id为自增长
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false,unique = true)
private String username;
@Column
private String password;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
④、创建Dao层
package com.example.demo.dao;
import com.example.demo.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserDao extends JpaRepository<User,Long> {
User findUserByName(String username);
}
⑤、创建Service层
package com.example.demo.service;
import com.example.demo.dao.UserDao;
import com.example.demo.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserDao userRepository;
public User findUserByName(String username) {
return userRepository.findUserByName(username);
}
}
⑥创建Contriller层
package com.example.demo.controller;
import com.example.demo.entity.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
@GetMapping("/{username}")
//@PathVariable可以获取RESTful风格的url路径上的参数
public User getUser(@PathVariable("username")String username) {
return userService.findUserByName(username);
}
}
⑦启动程序,控制台输出的日志如下
由此可见,JPA已经在数据库中创建了user表,查看数据库:
插入一条数据;
⑧,打开浏览器,在浏览器上输入“localhost:8080/user/daihu”,就可以在数据库 中读取username为“daihu”的用户对象,浏览器显示的数据如下: