JPA的全称是Java Persistence API,即Java持久化API,JSR编号338,具体使用可以参考官方文档。本文首先介绍在SpringBoot的简单使用,然后对实体间的关系进行讲述。
1. 简单使用
1.1 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
1.2 配置数据库的连接
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/jpatest
1.3 编写实体类
@Entity
@Table(name = "user")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) //avoid Exception
public class User{
@Id
@GeneratedValue
private Long id;
private String name;
private int age;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
1.3 编写Repository
这里只需要继承JpaRepository这个接口就能注入带有增删改查基本操作的实现类。
public interface UserRepository extends JpaRepository<User, Long> {
}
1.4 在Controller中使用
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("user/{id}")
public User getUser(@PathVariable long id){
User user = userRepository.getOne(id);
return user;
}
@GetMapping("all")
public List<User> findAllUsers(){
return userRepository.findAll();
}
}
2.实体间的关系
2.1 编写实体
实体间的关系分为单向和双向。此处只列举双向关系,现在有四个实体Employee, Cubicle, Department,Project。Employee与Cubicle为一对一(OneToOne)的关系,即员工与工位之间一一对应,且Employee为主控方;Employee与Department为多对一(ManyToOne)的关系,即一个部门里有多个员工,Department为主控方;Employee与Project为多对多(ManyToMany)的关系,即一个员工可以参与多个项目,一个项目里有多个员工,且Project为主控方。满足以上条件的各实体代码(省略getset方法)如下:
@Entity
public class Employee {
@Id
@GeneratedValue
private long id;
private String name;
private int age;
@OneToOne(cascade = CascadeType.ALL)
private Cubicle cubicle;
@ManyToOne(cascade = CascadeType.ALL)
private Department department;
@ManyToMany(mappedBy = "employees")
private Collection<Project> projects;
}
@Entity
public class Cubicle {
@Id
@GeneratedValue
private long id;
@OneToOne(mappedBy = "cubicle")
private Employee employee;
private String location;
}
@Entity
public class Department {
@Id
@GeneratedValue
private long id;
@OneToMany(mappedBy = "department")
private Collection<Employee> employees;
private String departName;
}
@Entity
public class Project {
@Id
@GeneratedValue
private long id;
@ManyToMany(cascade = CascadeType.ALL)
private Collection<Employee> employees;
private String projName;
注意:cascade写要主控方的字段注解上,表示级联操作。
2.2 编写Repository
public interface EmpoyeeRepository extends JpaRepository<Employee, Long> {
}
2.3 编写Controller
@RestController
public class EmployeeController {
@Autowired
private EmpoyeeRepository empoyeeRepository;
@PostMapping("/addEmployee")
public Employee addEmpoyee(@RequestBody Employee employee){
empoyeeRepository.save(employee);
return empoyeeRepository.getOne(employee.getId());
}
}
2.4 配置自动ddl操作
如果需要自动创建表则在SpringBoot主配置文件中增加下面的代码,表示每次启动时都会进行create-drop操作。
spring.jpa.hibernate.ddl-auto=create-drop
2.5 查看表结构
启动项目后可以在数据库中看到生成了employee,cubicle,department,project,project_employee,hibernate_sequence,hibernate_sequence六张表。
对于OneToOne和ManyToOne,会在主控方中以“被控方表名_id”形式添加字段,如employee表结构:
对于ManyToMany会创建一张中间表,如project_employess:
2.6 测试
在PostMan中Headers设置Content-Type
为Application/json;charset=UTF-8
,Body中写入以下内容
{"name":"Jay","age":16,"cubicle":{"location":"Wuhan"},"department":{"departName":"Java"},"projects":[{"projName":"Project1"},{"projName":"Project2"}]}
然后以http://localhost:8080/addEmployee
作为url发送post请求,则可以查看相应的数据库表中增加记录。
网友评论