Spring boot中使用MySQL数据库时
@Table:指定关联的数据库表名
@Id定义一条记录的唯一标识;并结合注解@GeneratedValue将其设置为自动生成
@Entity
@Table(name = "department")
public class Department{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
public Department(){
}
.....
}
@Entity
@Table(name = "user")
public class User implements java.io.Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createdate;
@ManyToOne // 多对一关系
@JoinColumn(name = "did") //数据库表中用字段did表示部门的ID
@JsonBackReference // 防止关系对象的递归访问
private Department department;
@ManyToMany(cascade = {}, fetch = FetchType.EAGER) // 用户与角色之间的多对多关系
@JoinTable(name = "user_role", // 并使用中间表user_role存储这种关系
joinColumns = {@JoinColumn(name = "user_id")},
inverseJoinColumns = {@JoinColumn(name = "roles_id")})
private List<Role> roles;
public User(){
}
}
@Entity
@Table(name = "role")
public class Role implements java.io.Serializabel{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
public Role(){
}
....
}
上面的实体定义,实现了使用Java普通对象与数据库表建立映射关系,接下来便可使用JPA实现持久化。
@RestController 提供实现了REST API
@RequestMapping 提供路由信息
@SpringBootApplication Spring Boot应用的标识