Spring Boot:使用Spring Data JPA读取数据会返回错误的值

时间:2017-01-20 16:24:03

标签: java hibernate spring-mvc spring-boot spring-data-jpa

我在我的应用程序中使用Spring Boot。我有一个访问服务层的控制器,它访问我的Spring Data JPA的CrudRepository实现,它与Hibernate交互以从数据库中获取数据。以下所有三个CrudRepository实现都返回不正确的对象:

public class ProductRepositoryImpl implements ProductRepository {

    @Autowired
    private SessionFactory sessionFactory;

    @SuppressWarnings("unchecked")
    public List<Product> findProductBatch(int start, int end) {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Product");
        query.setFirstResult(start);
        query.setMaxResults(end);
        List<Product> list = query.list();
        return list;
    }

    @SuppressWarnings({ "unused", "unchecked" })
    @Override
    public Iterable<Product> findAll() {
        Session session = sessionFactory.getCurrentSession();
        List<Product> products = session.createQuery("from Product").list();
        Iterable<Product> productIterable = products;
        return products;
    }

    @SuppressWarnings("unchecked")
    public List<Product> findBatch(int start, int end) {
        Session session = sessionFactory.getCurrentSession();
        Query query = session.createQuery("from Product");
        query.setFirstResult(start);
        query.setMaxResults(end);
        List<Product> list = query.list();
        return list;
    }

}

findOne()方法仅在传递给它的参数为零时才返回记录,而记录的id不为零。发送请求时返回以下JSON响应:

{
  "productId": 0,
  "name": "xxxxxx",
  "productCategoryId": null,
  "created": 1482655958000,
  "createdBy": null
}

该记录存在于数据库中,但其id为1且确实具有“productCategoryId”,但由于未注入,因此返回null。

findAll()方法重复多次重复相同的记录,findBatch()方法返回类似的响应。

以下是代码的其余部分:

Product.java:

@Entity
public class Product {

    @Id
    private Integer productId;
    private String name;
    private Integer productCategoryId;
    @OneToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "productCategoryId", insertable = false, updatable = false)
    @Autowired
    private ProductCategory productCategory;
    private Date created;
    private Integer createdBy;

    public Product() {
    }

    public Product(Integer productId, String name, ProductCategory productCategory, Integer uomId, Date created, Integer createdBy) {
        this.productId = productId;
        this.name = name;
        this.productCategory = productCategory;
        this.created = created;
        this.createdBy = createdBy;
    }

    public Product(String name, ProductCategory productCategory) {
        this.name = name;
        this.productCategory = productCategory;
    }

    public Integer getProductId() {
        return productId;
    }

    public void setProductId(Integer productId) {
        this.productId = productId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getProductCategoryId() {
        return productCategoryId;
    }

    public void setProductCategoryId(Integer productCategoryId) {
        this.productCategoryId = productCategoryId;
    }

//  public ProductCategory getProductCategory() {
//      return productCategory;
//  }
//
//  public void setProductCategory(ProductCategory productCategory) {
//      this.productCategory = productCategory;
//  }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Integer getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
}

ProductCategory.java:

    @Entity
    public class ProductCategory {

    @Id
    private Integer productCategoryId;
    private String name;
    private Date created;
    private Integer createdBy;

    public ProductCategory() {
    }

    public ProductCategory(Integer productCategoryId, String name, Date created, Integer createdBy) {
        this.productCategoryId = productCategoryId;
        this.name = name;
        this.created = created;
        this.createdBy = createdBy;
    }

    public Integer getProductCategoryId() {
        return productCategoryId;
    }

    public void setProductCategoryId(Integer productCategoryId) {
        this.productCategoryId = productCategoryId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Integer getCreatedBy() {
        return createdBy;
    }

    public void setCreatedBy(Integer createdBy) {
        this.createdBy = createdBy;
    }
}

ProductServiceImpl.java

@Service
@Transactional
public class ProductServiceImpl implements ProductService {



 @Autowired
     private ProductRepository productRepository;

    public Product findOne(int productId) {
        return productRepository.findOne(productId);
    }

    public List<Product> findAll() {
        List<Product> products = new ArrayList<>();
        productRepository.findAll().forEach(products::add);
        return products;
    }

    @Override
    public List<Product> findBatch(int start, int end) {
        return productRepository.findBatch(start, end);
    }
}

ProductController.java:

@RestController
@RequestMapping("/products")
@EnableTransactionManagement
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping(method = RequestMethod.GET)
    public List<Product> findAll() {
        List<Product> products = productService.findAll();
        return products;
    }

    @RequestMapping(value = "/{productId}", method = RequestMethod.GET)
    public Product findOne(@PathVariable int productId) {
        Product product = productService.findOne(productId);
        return product;
    }

    @RequestMapping(value = "/{start}/{end}", method = RequestMethod.GET)
    public List<Product> findBatch(@PathVariable int start, @PathVariable int end) {
        List<Product> list = productService.findBatch(start, end);
        return list;
    }
}

ApplicationContextConfig.java:

public class ApplicationContextConfig {

    @Bean
    public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) {
        HibernateJpaSessionFactoryBean factory = new HibernateJpaSessionFactoryBean();
        factory.setEntityManagerFactory(emf);
        return factory;
    }
}

响应还应该包含一个完全注入的ProductCategory对象,但它没有。

1 个答案:

答案 0 :(得分:1)

最后,解决方案是将其添加到我的application.properties文件中:

spring.jpa.hibernate.ddl-auto=validate
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

第一行检查列的存在而不改变其结构,而第二行更改Hibernate验证的默认命名策略,并避免向表名添加下划线。