다음과 같은 간단한 스프링 부트 코드가 있습니다. 왜 JPARepositoryImpl 코드 - JpaCustomerRepository가 호출되지 않습니다 (print 문을 추가하여 ..).왜 JPARepositoryImpl 코드가 호출되지 않습니까?
주 및 컨트롤러에 @ComponentScan을 추가했습니다. 제발 조언.
감사합니다,
@Entity
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(nullable = false)
private String product;
@Column(nullable = false)
private String charge;
protected Customer() {
}
public Customer(String product) {
this.product = product;
}
public Long getId() {
return id;
}
public String getProduct() {
return this.product;
}
public String getCharge() {
return this.charge;
}}
public interface CustomerRepository extends Repository<Customer, Long> {
List<Customer> findAll();
}
@Repository
class JpaCustomerRepository implements CustomerRepository {
@PersistenceContext
private EntityManager em;
@Override
public List<Customer> findAll() {
TypedQuery<Customer> query = em.createQuery("select c from Customer c",
Customer.class);
return query.getResultList();
}
}
@Configuration
@ComponentScan
@EnableAutoConfiguration
public class SampleDataJpaApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleDataJpaApplication.class, args);
}
}
@Controller
@ComponentScan
@RequestMapping("/customers")
public class SampleController {
private CustomerRepository customerRepository;
@Autowired
public SampleController(CustomerRepository customerRepository) {
this.customerRepository = customerRepository;
}
@RequestMapping("/list")
public String list(Model model) {
model.addAttribute("customers", this.customerRepository.findAll());
return "customers/list";
}
}
그러나 책 봄 데이터의 샘플 코드 (JpaCustomerRepository가) 전화를받을 않았다. 그 잡은 거니?
@MappedSuperclass
public class AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
/**
* Returns the identifier of the entity.
*
* @return the id
*/
public Long getId() {
return id;
}
/*
* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (this.id == null || obj == null || !(this.getClass().equals(obj.getClass()))) {
return false;
}
AbstractEntity that = (AbstractEntity) obj;
return this.id.equals(that.getId());
}
/*
* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return id == null ? 0 : id.hashCode();
}
}
@Entity
public class Customer extends AbstractEntity {
private String firstname, lastname;
@Column(unique = true)
private EmailAddress emailAddress;
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "customer_id")
private Set<Address> addresses = new HashSet<Address>();
/**
* Creates a new {@link Customer} from the given firstname and lastname.
*
* @param firstname must not be {@literal null} or empty.
* @param lastname must not be {@literal null} or empty.
*/
public Customer(String firstname, String lastname) {
Assert.hasText(firstname);
Assert.hasText(lastname);
this.firstname = firstname;
this.lastname = lastname;
}
protected Customer() {
}
/**
* Adds the given {@link Address} to the {@link Customer}.
*
* @param address must not be {@literal null}.
*/
public void add(Address address) {
Assert.notNull(address);
this.addresses.add(address);
}
/**
* Returns the firstname of the {@link Customer}.
*
* @return
*/
public String getFirstname() {
return firstname;
}
/**
* Returns the lastname of the {@link Customer}.
*
* @return
*/
public String getLastname() {
return lastname;
}
/**
* Sets the lastname of the {@link Customer}.
*
* @param lastname
*/
public void setLastname(String lastname) {
this.lastname = lastname;
}
/**
* Returns the {@link EmailAddress} of the {@link Customer}.
*
* @return
*/
public EmailAddress getEmailAddress() {
return emailAddress;
}
/**
* Sets the {@link Customer}'s {@link EmailAddress}.
*
* @param emailAddress must not be {@literal null}.
*/
public void setEmailAddress(EmailAddress emailAddress) {
this.emailAddress = emailAddress;
}
/**
* Return the {@link Customer}'s addresses.
*
* @return
*/
public Set<Address> getAddresses() {
return Collections.unmodifiableSet(addresses);
}
}
public interface CustomerRepository extends Repository<Customer, Long> {
/**
* Returns the {@link Customer} with the given identifier.
*
* @param id the id to search for.
* @return
*/
Customer findOne(Long id);
/**
* Saves the given {@link Customer}.
*
* @param customer the {@link Customer} to search for.
* @return
*/
Customer save(Customer customer);
/**
* Returns the customer with the given {@link EmailAddress}.
*
* @param emailAddress the {@link EmailAddress} to search for.
* @return
*/
Customer findByEmailAddress(EmailAddress emailAddress);
}
@Repository
class JpaCustomerRepository implements CustomerRepository {
@PersistenceContext
private EntityManager em;
/*
* (non-Javadoc)
* @see com.oreilly.springdata.jpa.core.CustomerRepository#findOne(java.lang.Long)
*/
@Override
public Customer findOne(Long id) {
return em.find(Customer.class, id);
}
/*
* (non-Javadoc)
* @see com.oreilly.springdata.jpa.core.CustomerRepository#save(com.oreilly.springdata.jpa.core.Customer)
*/
public Customer save(Customer customer) {
if (customer.getId() == null) {
em.persist(customer);
return customer;
} else {
return em.merge(customer);
}
}
/*
* (non-Javadoc)
* @see com.oreilly.springdata.jpa.core.CustomerRepository#findByEmailAddress(com.oreilly.springdata.jpa.core.EmailAddress)
*/
@Override
public Customer findByEmailAddress(EmailAddress emailAddress) {
TypedQuery<Customer> query = em.createQuery("select c from Customer c where c.emailAddress = :email",
Customer.class);
query.setParameter("email", emailAddress);
return query.getSingleResult();
}
}
원본 코드 시험 방법,
@ContextConfiguration(classes = PlainJpaConfig.class)
public class JpaCustomerRepositoryIntegrationTest extends AbstractIntegrationTest {
@Autowired
CustomerRepository repository;
@Test
public void insertsNewCustomerCorrectly() {
Customer customer = new Customer("Alicia", "Keys");
customer = repository.save(customer);
assertThat(customer.getId(), is(notNullValue()));
}
@Test
public void updatesCustomerCorrectly() {
Customer dave = repository.findByFirstname("Dave");
assertThat(dave, is(notNullValue()));
dave.setLastname("Miller");
dave = repository.save(dave);
Customer reference = repository.findByFirstname(dave.getFirstname());
assertThat(reference.getLastname(), is(dave.getLastname()));
}
}
내 주요 방법 코드,
@Configuration
@ComponentScan
@EnableAutoConfiguration
@ContextConfiguration(classes = PlainJpaConfig.class)
public class SampleDataJpaApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleDataJpaApplication.class, args);
}
}
나는 원래 코드가 추가 @EnableAutoConfiguration이없는 한 어떤? 이것이 이유일까요? 하지만 @EnableAutoConfiguration이 없으면 스프링 부트 컨테이너를 시작할 수 없습니다.
그러나 스프링 데이터의 샘플 코드 (JpaCustomerRepository)가 호출되었습니다. 그 잡은 거니? 내 원래 게시물을 참조하십시오. – johnsam
내 생각에, 원래 코드에서 Spring 데이터는 리포지토리에 대한 구현을 자동으로 제공하도록 구성되지 않았지만 코드에서 Spring Boot는 자동으로이 기능에 대한 Spring 데이터를 구성합니다. 책 코드 구성을 게시 할 수 있습니까? – geoand
이러한 주석 이외의 Spring 데이터에는 많은 구성이 없습니다. 원래 코드에없는 추가 EnableAutoConfiguration이 있습니까? 이것이 이유일까요? 하지만 EnableAutoConfiguration이 없으면 스프링 부트 컨테이너를 시작할 수 없습니다. 원래 게시물의 코드를 업데이트했습니다. – johnsam