我是Spring的新手,并且想基于Spring Boot创建一个小的Restful api。
我已经建立了mysql数据库并成功连接到我的项目。在设置实体之间的关系时遇到麻烦。
package ca.mcmcaster.xb3l02g06.DineSafeChicago.inspection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import ca.mcmcaster.xb3l02g06.DineSafeChicago.restaurant.Restaurant;
@Entity
public class Inspection {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "inspection_id")
private Long id;
// @ManyToOne
// @JoinColumn(name="restaurant_id")
// private Restaurant restaurant;
private String result;
private String violation;
private Date time;
@Override
public String toString() {
return "Inspection [result=" + result + ", time=" + time + "]";
}
protected Inspection() {
}
public Inspection(String result, String violation, String timeStr) {
this.result = result;
this.violation = violation;
this.time = parseTime(timeStr);
}
// public void setRestaurant(Restaurant restaurant) {
// this.restaurant = restaurant;
// }
public String getResult() {
return result;
}
public String getViolation() {
return violation;
}
public Date getTime() {
return time;
}
private Date parseTime(String dateStr) {
SimpleDateFormat parser = new SimpleDateFormat("MM/dd/yyyy");
Date time = null;
try {
time = parser.parse(dateStr);
} catch (ParseException e) {
System.out.println("Unparseable using " + dateStr);
}
return time;
}
}
我想为每家餐厅进行相关的多重检查。
package ca.mcmcaster.xb3l02g06.DineSafeChicago.restaurant;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import ca.mcmcaster.xb3l02g06.DineSafeChicago.inspection.Inspection;
@Entity
public class Restaurant implements Comparable<Restaurant> {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "restaurant_id")
private Long id;
private String name;
private int zip;
private double latitude;
private double longitude;
// private ArrayList<Inspection> inspections;
// private ArrayList<Crime> crimes;
private double foodSafetyScore;
private double neighborhoodSafetyScore;
private double overallScore;
private boolean closed;
// @OneToMany(mappedBy = "restaurant", cascade = CascadeType.ALL,targetEntity = Inspection.class)
// private List<Inspection> inspections;
protected Restaurant() {
}
public Restaurant(String name, int zip, double latitude, double longitude) {
this.name = name;
this.zip = zip;
this.latitude = latitude;
this.longitude = longitude;
this.closed = false;
this.foodSafetyScore = 0;
this.neighborhoodSafetyScore = 0;
}
// public void addInspection(Inspection ins) {
// inspections.add(ins);
// ins.setRestaurant(this);
// }
// public List<Inspection> getInspections() {
// return inspections;
// }
public String getName() {
return name;
}
public int getZip() {
return zip;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public double getNeighborhoodSafetyScore() {
return neighborhoodSafetyScore;
}
public double getOverallScore() {
return overallScore;
}
public boolean isClosed() {
return isClosed();
}
public int compareTo(Restaurant other) {
return Double.compare(overallScore, other.overallScore);
}
@Override
public String toString() {
return "Restaurant [name=" + name + ", overallScore=" + overallScore + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Restaurant other = (Restaurant) obj;
if (id != other.id)
return false;
if (Double.doubleToLongBits(latitude) != Double.doubleToLongBits(other.latitude))
return false;
if (Double.doubleToLongBits(longitude) != Double.doubleToLongBits(other.longitude))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (zip != other.zip)
return false;
return true;
}
}
我想做一个快速测试(将一些数据插入数据库),如下:
package ca.mcmcaster.xb3l02g06.DineSafeChicago.inspection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import ca.mcmcaster.xb3l02g06.DineSafeChicago.restaurant.Restaurant;
import ca.mcmcaster.xb3l02g06.DineSafeChicago.restaurant.RestaurantRepository;
@SpringBootApplication
public class Gen implements CommandLineRunner {
@Autowired
private InspectionRepository inspectionRepo;
@Autowired
private RestaurantRepository restaurantRepo;
public static void main(String[] args) {
SpringApplication.run(Gen.class, args);
}
// @Bean
// public CommandLineRunner demo(InspectionRepository repository) {
// return (args) -> {
// Inspection i1 = new Inspection("pass", "no comment", "11/04/1998");
// Inspection i2 = new Inspection("pass with condition", "no comment", "11/04/2019");
// Inspection i3 = new Inspection("fail", "no comment", "11/04/2001");
// repository.save(i1);
// repository.save(i2);
// repository.save(i3);
// System.out.println("All saved!");
// for (Inspection ins : repository.findAll()) {
// System.out.println(ins);
// }
//// Restaurant r1 = new Restaurant("asd", 100, 12.2, 12.2);
// };
// }
@Override
public void run(String[] args) throws Exception {
Restaurant r1 = new Restaurant("asd", 100, 12.2, 12.2);
Inspection i1 = new Inspection("pass", "no comment", "11/04/1998");
Inspection i2 = new Inspection("pass with condition", "no comment", "11/04/2019");
// r1.addInspection(i1);
// r1.addInspection(i2);
restaurantRepo.save(r1);
}
}
但是我通过搜索所有答案来更改代码, 运行spring应用程序时,总是收到错误消息:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: @OneToOne or @ManyToOne on ca.mcmcaster.xb3l02g06.DineSafeChicago.inspection.Inspection.restaurant references an unknown entity: ca.mcmcaster.xb3l02g06.DineSafeChicago.restaurant.Restaurant
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1762) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lamb
......
Caused by: org.hibernate.AnnotationException: @OneToOne or @ManyToOne on ca.mcmcaster.xb3l02g06.DineSafeChicago.inspection.Inspection.restaurant references an unknown entity: ca.mcmcaster.xb3l02g06.DineSafeChicago.restaurant.Restaurant
at org.hibernate.cfg.ToOneFkSecondPass.doSecondPass(ToOneFkSecondPass.java:97) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processEndOfQueue(InFlightMetadataCollectorImpl.java:1827) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processFkSecondPassesInOrder(InFlightMetadataCollectorImpl.java:1771) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1658) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:287) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
真的很感谢任何有用的提示!