将@OneToMany 用于使用 Spring Boot 和 MySQL 的 Web 应用程序会导致创建 bean 出错
Using @OneToMany for a Web Application Using Spring Boot and MySQL is giving error creating bean
我正在尝试将多个 CreditCards 连接到同一个用户,但是在编译程序时出现创建 bean 错误。
用户Class
package com.bookstore.BookStoreDemo.model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "Users")
public class User {
@Id
@Column(name = "username", updatable = false, nullable = false)
private String username;
@Column(name = "password")
private String password;
@Column(name = "name")
private String name;
@Column(name = "address")
private String address;
@Column(name = "email")
private String email;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "user", referencedColumnName = "username")
List<CreditCard> creditCard = new ArrayList<>();
//For Deserialization
public User() {
}
public User(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
信用卡Class
import javax.persistence.*;
import java.math.BigInteger;
@Entity
@Table(name = "CreditCards")
public class CreditCard {
@Id
@Column(name = "username")
private String username;
@Column(name = "cardNumber")
private BigInteger cardNumber;
@Column(name = "expirationDate")
private Integer expirationDate;
@Column(name = "securityCode")
private Integer securityCode;
//For Deserialization
public CreditCard() {}
public CreditCard(String username) {
this.username = username;
}
public BigInteger getCardNumber() {
return cardNumber;
}
public void setCardNumber(BigInteger cardNumber) {
this.cardNumber = cardNumber;
}
public Integer getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Integer expirationDate) {
this.expirationDate = expirationDate;
}
public Integer getSecurityCode() {
return securityCode;
}
public void setSecurityCode(Integer securityCode) {
this.securityCode = securityCode;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
用户资源Class
package com.bookstore.BookStoreDemo.resource;
import com.bookstore.BookStoreDemo.model.User;
import com.bookstore.BookStoreDemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping(value = "/geektext")
public class UserResource {
@Autowired
private UserRepository userRepository;
//Displays User By Username Search
@GetMapping("/users/{username}")
public Optional<User> getUserByUsername(@PathVariable String username) {
Optional<User> users = userRepository.findByUsername(username);
if (users.isPresent()) {
return userRepository.findByUsername(username);
} else{
throw new RuntimeException("User '" + username + "' not found");
}
}
//Displays User By Name Search
@GetMapping("/users/{name}")
public Optional<User> getUserByName(@PathVariable String name) {
Optional<User> users = userRepository.findByName(name);
if (users.isPresent()) {
return userRepository.findByName(name);
} else{
throw new RuntimeException("User '" + name + "' not found");
}
}
//Displays List of All Users
@GetMapping("/users")
public List<User> getAllUsers() {
return userRepository.findAll();
}
//Creates a New User
@PostMapping("/users")
public User loadUser(@RequestBody final User user) {
user.setEmail(user.getUsername());
return userRepository.save(user);
}
//Creates a List of New Users
@PostMapping("/users/all")
public List <User> loadAllUsers(@RequestBody final List <User> users) {
return userRepository.saveAll(users);
}
//Updates an Existing User
@PutMapping("/users")
public User updateUser(@RequestBody User user) {
return userRepository.save(user);
}
//Deletes an Existing User
@DeleteMapping("/users/{username}")
public String deleteUser(@PathVariable String username) {
Optional<User> users = userRepository.findById(username);
if (users.isPresent()) {
userRepository.delete(users.get());
return "User '" + username + "' has been deleted";
} else {
throw new RuntimeException("User '" + username + "' not found");
}
}
}
信用卡资源Class
package com.bookstore.BookStoreDemo.resource;
import com.bookstore.BookStoreDemo.model.CreditCard;
import com.bookstore.BookStoreDemo.model.User;
import com.bookstore.BookStoreDemo.repository.CreditCardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping(value = "/geektext/users")
class CreditCardResource {
@Autowired
CreditCardRepository cardsRepository;
User user = new User();
//Displays CreditCard By Username Search
@GetMapping("/{username}/cards")
public Optional<CreditCard> getCardsByUsername(@PathVariable String username) {
Optional<CreditCard> cards = cardsRepository.findByUsername(username);
if (user.getUsername().matches(username)) {
return cardsRepository.findByUsername(username);
} else{
throw new RuntimeException("User '" + username + "' not found");
}
}
//Displays CreditCard By Name Search
@GetMapping("/{name}/cards")
public Optional<CreditCard> getCardsByName(@PathVariable String name) {
Optional<CreditCard> cards = cardsRepository.findByName(name);
if (user.getName().matches(name)) {
return cardsRepository.findByName(name);
} else{
throw new RuntimeException("User '" + name + "' not found");
}
}
//Creates New Card for User
@PostMapping("/{username}/cards")
public CreditCard loadCard(@RequestBody CreditCard cards, @PathVariable("name") final String username) {
if (username.equals(user.getUsername())) {
return cardsRepository.save(cards);
} else{
throw new RuntimeException("User '" + username + "' not found");
}
}
}
用户存储库接口
package com.bookstore.BookStoreDemo.repository;
import com.bookstore.BookStoreDemo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, String> {
Optional<User> findByName(String name);
Optional<User> findByUsername(String username);
}
CreditCardRepository 接口
package com.bookstore.BookStoreDemo.repository;
import com.bookstore.BookStoreDemo.model.CreditCard;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface CreditCardRepository extends JpaRepository<CreditCard, String> {
Optional<CreditCard> findByName(String name);
Optional<CreditCard> findByUsername(String username);
}
主要
package com.bookstore.BookStoreDemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BookStoreDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BookStoreDemoApplication.class, args);
}
}
pom.xlm 文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>GeekText</groupId>
<artifactId>Bookstore</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Bookstore</name>
<description>Project for a Bookstore using Spring Boot</description>
<properties>
<java.version>14</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
代码编译时出现如下错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.bookstore.BookStoreDemo.repository.CreditCardRepository.findByName(java.lang.String)! No property name found for type CreditCard!
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:176) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:101) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1827) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getObjectForBeanInstance(AbstractAutowireCapableBeanFactory.java:1265) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:334) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:624) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:612) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:51) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:36) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:404) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:361) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:898) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:554) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at com.bookstore.BookStoreDemo.BookStoreDemoApplication.main(BookStoreDemoApplication.java:10) ~[classes/:na]
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.bookstore.BookStoreDemo.repository.CreditCardRepository.findByName(java.lang.String)! No property name found for type CreditCard!
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:96) ~[spring-data-jpa-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:107) ~[spring-data-jpa-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:218) ~[spring-data-jpa-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:81) ~[spring-data-jpa-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:99) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery(QueryExecutorMethodInterceptor.java:92) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at java.base/java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:195) ~[na:na]
at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133) ~[na:na]
at java.base/java.util.Collections$UnmodifiableCollection.forEachRemaining(Collections.java:1056) ~[na:na]
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.mapMethodsToQuery(QueryExecutorMethodInterceptor.java:94) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$new[=20=](QueryExecutorMethodInterceptor.java:84) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at java.base/java.util.Optional.map(Optional.java:258) ~[na:na]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.<init>(QueryExecutorMethodInterceptor.java:84) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:331) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet(RepositoryFactoryBeanSupport.java:297) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:212) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.util.Lazy.get(Lazy.java:94) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:244) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:57) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:169) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
... 24 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property name found for type CreditCard!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:94) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:382) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:358) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.mapping.PropertyPath.lambda$from[=20=](PropertyPath.java:311) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at java.base/java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:330) ~[na:na]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:293) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:276) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:82) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.query.parser.PartTree$OrPart.lambda$new[=20=](PartTree.java:251) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at java.base/java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:195) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:177) ~[na:na]
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na]
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:252) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.query.parser.PartTree$Predicate.lambda$new[=20=](PartTree.java:381) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at java.base/java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:195) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:177) ~[na:na]
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na]
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:382) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:97) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:89) ~[spring-data-jpa-2.3.2.RELEASE.jar:2.3.2.RELEASE]
... 49 common frames omitted
从 CreditCard 中删除以下代码
//Optional<User> findByName(String name);
修改 CreditCardResource
//Displays CreditCard By Name Search
@GetMapping("/{name}/cards")
public Optional<CreditCard> getCardsByName(@PathVariable String name) {
Optional<CreditCard> cards = cardsRepository.findByUsername(name);
if (user.getName().matches(name)) {
return cardsRepository.findByUsername(name);
} else {
throw new RuntimeException("User '" + name + "' not found");
}
}
我正在尝试将多个 CreditCards 连接到同一个用户,但是在编译程序时出现创建 bean 错误。
用户Class
package com.bookstore.BookStoreDemo.model;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
@Entity
@Table(name = "Users")
public class User {
@Id
@Column(name = "username", updatable = false, nullable = false)
private String username;
@Column(name = "password")
private String password;
@Column(name = "name")
private String name;
@Column(name = "address")
private String address;
@Column(name = "email")
private String email;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "user", referencedColumnName = "username")
List<CreditCard> creditCard = new ArrayList<>();
//For Deserialization
public User() {
}
public User(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
信用卡Class
import javax.persistence.*;
import java.math.BigInteger;
@Entity
@Table(name = "CreditCards")
public class CreditCard {
@Id
@Column(name = "username")
private String username;
@Column(name = "cardNumber")
private BigInteger cardNumber;
@Column(name = "expirationDate")
private Integer expirationDate;
@Column(name = "securityCode")
private Integer securityCode;
//For Deserialization
public CreditCard() {}
public CreditCard(String username) {
this.username = username;
}
public BigInteger getCardNumber() {
return cardNumber;
}
public void setCardNumber(BigInteger cardNumber) {
this.cardNumber = cardNumber;
}
public Integer getExpirationDate() {
return expirationDate;
}
public void setExpirationDate(Integer expirationDate) {
this.expirationDate = expirationDate;
}
public Integer getSecurityCode() {
return securityCode;
}
public void setSecurityCode(Integer securityCode) {
this.securityCode = securityCode;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
用户资源Class
package com.bookstore.BookStoreDemo.resource;
import com.bookstore.BookStoreDemo.model.User;
import com.bookstore.BookStoreDemo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping(value = "/geektext")
public class UserResource {
@Autowired
private UserRepository userRepository;
//Displays User By Username Search
@GetMapping("/users/{username}")
public Optional<User> getUserByUsername(@PathVariable String username) {
Optional<User> users = userRepository.findByUsername(username);
if (users.isPresent()) {
return userRepository.findByUsername(username);
} else{
throw new RuntimeException("User '" + username + "' not found");
}
}
//Displays User By Name Search
@GetMapping("/users/{name}")
public Optional<User> getUserByName(@PathVariable String name) {
Optional<User> users = userRepository.findByName(name);
if (users.isPresent()) {
return userRepository.findByName(name);
} else{
throw new RuntimeException("User '" + name + "' not found");
}
}
//Displays List of All Users
@GetMapping("/users")
public List<User> getAllUsers() {
return userRepository.findAll();
}
//Creates a New User
@PostMapping("/users")
public User loadUser(@RequestBody final User user) {
user.setEmail(user.getUsername());
return userRepository.save(user);
}
//Creates a List of New Users
@PostMapping("/users/all")
public List <User> loadAllUsers(@RequestBody final List <User> users) {
return userRepository.saveAll(users);
}
//Updates an Existing User
@PutMapping("/users")
public User updateUser(@RequestBody User user) {
return userRepository.save(user);
}
//Deletes an Existing User
@DeleteMapping("/users/{username}")
public String deleteUser(@PathVariable String username) {
Optional<User> users = userRepository.findById(username);
if (users.isPresent()) {
userRepository.delete(users.get());
return "User '" + username + "' has been deleted";
} else {
throw new RuntimeException("User '" + username + "' not found");
}
}
}
信用卡资源Class
package com.bookstore.BookStoreDemo.resource;
import com.bookstore.BookStoreDemo.model.CreditCard;
import com.bookstore.BookStoreDemo.model.User;
import com.bookstore.BookStoreDemo.repository.CreditCardRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Optional;
@RestController
@RequestMapping(value = "/geektext/users")
class CreditCardResource {
@Autowired
CreditCardRepository cardsRepository;
User user = new User();
//Displays CreditCard By Username Search
@GetMapping("/{username}/cards")
public Optional<CreditCard> getCardsByUsername(@PathVariable String username) {
Optional<CreditCard> cards = cardsRepository.findByUsername(username);
if (user.getUsername().matches(username)) {
return cardsRepository.findByUsername(username);
} else{
throw new RuntimeException("User '" + username + "' not found");
}
}
//Displays CreditCard By Name Search
@GetMapping("/{name}/cards")
public Optional<CreditCard> getCardsByName(@PathVariable String name) {
Optional<CreditCard> cards = cardsRepository.findByName(name);
if (user.getName().matches(name)) {
return cardsRepository.findByName(name);
} else{
throw new RuntimeException("User '" + name + "' not found");
}
}
//Creates New Card for User
@PostMapping("/{username}/cards")
public CreditCard loadCard(@RequestBody CreditCard cards, @PathVariable("name") final String username) {
if (username.equals(user.getUsername())) {
return cardsRepository.save(cards);
} else{
throw new RuntimeException("User '" + username + "' not found");
}
}
}
用户存储库接口
package com.bookstore.BookStoreDemo.repository;
import com.bookstore.BookStoreDemo.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserRepository extends JpaRepository<User, String> {
Optional<User> findByName(String name);
Optional<User> findByUsername(String username);
}
CreditCardRepository 接口
package com.bookstore.BookStoreDemo.repository;
import com.bookstore.BookStoreDemo.model.CreditCard;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface CreditCardRepository extends JpaRepository<CreditCard, String> {
Optional<CreditCard> findByName(String name);
Optional<CreditCard> findByUsername(String username);
}
主要
package com.bookstore.BookStoreDemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class BookStoreDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BookStoreDemoApplication.class, args);
}
}
pom.xlm 文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>GeekText</groupId>
<artifactId>Bookstore</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>Bookstore</name>
<description>Project for a Bookstore using Spring Boot</description>
<properties>
<java.version>14</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
代码编译时出现如下错误:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'creditCardRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.bookstore.BookStoreDemo.repository.CreditCardRepository.findByName(java.lang.String)! No property name found for type CreditCard!
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:176) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:101) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1827) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getObjectForBeanInstance(AbstractAutowireCapableBeanFactory.java:1265) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:334) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:624) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:612) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:51) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:36) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:404) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:361) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:898) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:554) ~[spring-context-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at com.bookstore.BookStoreDemo.BookStoreDemoApplication.main(BookStoreDemoApplication.java:10) ~[classes/:na]
Caused by: java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.Optional com.bookstore.BookStoreDemo.repository.CreditCardRepository.findByName(java.lang.String)! No property name found for type CreditCard!
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:96) ~[spring-data-jpa-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:107) ~[spring-data-jpa-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:218) ~[spring-data-jpa-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:81) ~[spring-data-jpa-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lookupQuery(QueryExecutorMethodInterceptor.java:99) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$mapMethodsToQuery(QueryExecutorMethodInterceptor.java:92) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at java.base/java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:195) ~[na:na]
at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133) ~[na:na]
at java.base/java.util.Collections$UnmodifiableCollection.forEachRemaining(Collections.java:1056) ~[na:na]
at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.mapMethodsToQuery(QueryExecutorMethodInterceptor.java:94) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.lambda$new[=20=](QueryExecutorMethodInterceptor.java:84) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at java.base/java.util.Optional.map(Optional.java:258) ~[na:na]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.<init>(QueryExecutorMethodInterceptor.java:84) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:331) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet(RepositoryFactoryBeanSupport.java:297) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:212) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.util.Lazy.get(Lazy.java:94) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:244) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:57) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:169) ~[spring-beans-5.2.8.RELEASE.jar:5.2.8.RELEASE]
... 24 common frames omitted
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property name found for type CreditCard!
at org.springframework.data.mapping.PropertyPath.<init>(PropertyPath.java:94) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:382) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.mapping.PropertyPath.create(PropertyPath.java:358) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.mapping.PropertyPath.lambda$from[=20=](PropertyPath.java:311) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at java.base/java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:330) ~[na:na]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:293) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.mapping.PropertyPath.from(PropertyPath.java:276) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.query.parser.Part.<init>(Part.java:82) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.query.parser.PartTree$OrPart.lambda$new[=20=](PartTree.java:251) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at java.base/java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:195) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:177) ~[na:na]
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na]
at org.springframework.data.repository.query.parser.PartTree$OrPart.<init>(PartTree.java:252) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.query.parser.PartTree$Predicate.lambda$new[=20=](PartTree.java:381) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at java.base/java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:195) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.accept(ReferencePipeline.java:177) ~[na:na]
at java.base/java.util.Spliterators$ArraySpliterator.forEachRemaining(Spliterators.java:948) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474) ~[na:na]
at java.base/java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:913) ~[na:na]
at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234) ~[na:na]
at java.base/java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:578) ~[na:na]
at org.springframework.data.repository.query.parser.PartTree$Predicate.<init>(PartTree.java:382) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.repository.query.parser.PartTree.<init>(PartTree.java:97) ~[spring-data-commons-2.3.2.RELEASE.jar:2.3.2.RELEASE]
at org.springframework.data.jpa.repository.query.PartTreeJpaQuery.<init>(PartTreeJpaQuery.java:89) ~[spring-data-jpa-2.3.2.RELEASE.jar:2.3.2.RELEASE]
... 49 common frames omitted
从 CreditCard 中删除以下代码
//Optional<User> findByName(String name);
修改 CreditCardResource
//Displays CreditCard By Name Search
@GetMapping("/{name}/cards")
public Optional<CreditCard> getCardsByName(@PathVariable String name) {
Optional<CreditCard> cards = cardsRepository.findByUsername(name);
if (user.getName().matches(name)) {
return cardsRepository.findByUsername(name);
} else {
throw new RuntimeException("User '" + name + "' not found");
}
}