JPA有哪些注解?代码举例讲解

JPA有以下常用注解:

  1. @Entity:将类定义为实体。
@Entity
public class User { ... }
  1. @Table:指定实体对应的数据库表名。
@Entity  
@Table(name = "USER_INFO") 
public class User { ... } 
  1. @Id:将字段定义为主键。
@Entity
public class User {  
    @Id 
    private int id;  
}
  1. @GeneratedValue:指定主键生成策略。
@Entity  
public class User {  
    @Id 
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;  
}
  1. @Column:指定字段对应数据库的列名及属性。
@Entity  
public class User {  
    @Id
    private int id; 

    @Column(name = "USER_NAME", nullable = false, unique = true)
    private String name;
} 
  1. @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;
}
  1. @NamedQuery、@NamedNativeQuery、@NamedStoredProcedureQuery:定义JPQL查询、本地SQL查询、存储过程。
@Entity 
@NamedQuery(name = "User.findAll", query = "SELECT u FROM User u")
public class User { ... }