Spring data jpa使用注意事项

                        spring data jpa使用注意事项

  1. repository应该继承JpaRepository接口,可以使用Spring data jpa自带的方法。
  2. entity中对应表的主键字段的属性上应该加上@Id和@GeneratedValue注解,否则会报错,错误信息如下:
    org.springframework.beans.factory.BeanCreationException: 
    Error creating bean with name 'entityManagerFactory' defined in class path resource 
    [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: 
    Invocation of init method failed; nested exception is org.hibernate.AnnotationException:
     No identifier specified for entity: com.example.entity.User
    如果主键是自增,可以将strategy设置成GenerationType.IDENTITY,代码如下:
            @Id
    	@GeneratedValue(strategy=GenerationType.IDENTITY)
    	private int id;
  3. repository接口中即使是简单的对数据排序的方法,也需要加上By,如
    List<User> findAllByOrderByCreateTimeDesc();
  4. 如果需要使用复杂的查询时,可以让repository接口可以同时继承JpaSpecificationExecutor接口,如
    @Repository
    public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {
    }
    
    5. eclipse逆向生成实体类的方法,详情参考文章: eclipse逆向生成实体类

猜你喜欢

转载自blog.csdn.net/hsg_happyLearning/article/details/80280650