项目地址:https://github.com/heng1234/springdata-jpa
问题描述:
刚开始实体类代码是这样写的
package com.hvly.springjp_1.com.hlvy.entity;
import lombok.Data;
import javax.persistence.*;
/**
* Customer
*
* @author heng
**/
/**
* 1、在@Entity下增加@NamedQuery定义 需要注意 query里面的值也是JPQL 查询参数也要和实体类对应起来
* 因为实际场景中这种破坏ENtity的侵入式很不美 也不方便 所以这种方式容易一万 工作中也很少推荐
* 2、与之相对应的还有@NamedNativeQuery 用法一样 唯一不同的是 query里面放置的是原生SQL语句 而非实体类的字段名字
* name query的名称 规则:实体类.方法名`
*/
@NamedQuery(name = "Customer.findByFirstName",
query = "select c from Customer c where c.firstaname = ?1")
//@Data
@Entity
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)//自动增递
private Long id;
private String firstname;
private String lastname;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
CustomerJpaRepository
package com.hvly.springjp_1.com.hlvy.repository;
import com.hvly.springjp_1.com.hlvy.entity.Customer;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* Customer
*
* @author heng
**/
public interface CustomerJpaRepository extends JpaRepository<Customer,Long>{
/**
* @NamedQuery查询
* @param firstName
* @return
*/
Customer findByFirstName(String firstName);
}
Controller
package com.hvly.springjp_1.com.hlvy.controller;
import com.hvly.springjp_1.com.hlvy.entity.Customer;
import com.hvly.springjp_1.com.hlvy.repository.CustomerJpaRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* CustomerController
*
* @author heng
**/
@RestController
@RequestMapping("customer")
public class CustomerController {
@Autowired
private CustomerJpaRepository customerJpaRepository;
/**
* @NamedQuery查询
* @param firstName
* @return
*/
@RequestMapping("findByFirstName")
Customer findByFirstName(String firstName){
return customerJpaRepository.findByFirstName(firstName);
}
}
结果启动报错: sql打印出来 from后面跟的是实体类路径
接着我去网上看到这个https://blog.csdn.net/uhb6577/article/details/78998883
发现我已经加了@Entity注解
最后发现@NamedQuery(name = "Customer.findByFirstName",
query = "select c from Customer c where c.firstaname = ?1")
多写了个字母a 应该是 where c.firstname = ?1 而不是 where c.firstaname = ?1