JPA有以下常用注解:
- @Entity:将类定义为实体。
@Entity
public class User { ... }
- @Table:指定实体对应的数据库表名。
@Entity
@Table(name = "USER_INFO")
public class User { ... }
- @Id:将字段定义为主键。
@Entity
public class User {
@Id
private int id;
}
- @GeneratedValue:指定主键生成策略。
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
}
- @Column:指定字段对应数据库的列名及属性。
@Entity
public class User {
@Id
private int id;
@Column(name = "USER_NAME", nullable = false, unique = true)
private String name;
}
- @OneToOne、@OneToMany、@ManyToOne、@ManyToMany:定义对象关系映射。
@Entity
public class User {
@Id
private int id;
@OneToMany(mappedBy = "user")
private Set<Order> orders;
}
@Entity
public class Order {
@Id
private int id;
@ManyToOne
private User user;
}
- @NamedQuery、@NamedNativeQuery、@NamedStoredProcedureQuery:定义JPQL查询、本地SQL查询、存储过程。
@Entity
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User { ... }