我正在做学校项目,需要使用JPA。我有这样的架构:
客户.java
@Data
@Entity(name = "CUSTOMER")
public class Customer {
@Id
@Column(name = "CUSTOMER_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long customerId;
@Column(name = "NAME")
private String name;
@Column(name = "SURNAME")
private String surname;
@Column(name = "STREET")
private String street;
@Column(name = "CITY")
private String city;
@Column(name = "ZIP_CODE")
private String zipCode;
@Column(name = "COUNTRY")
private String country;
@OneToMany(mappedBy="customer",targetEntity=Order.class, fetch= FetchType.EAGER)
private Collection orders;
}
和Order.java
@Data
@Entity(name = "ORDER")
public class Order {
@Id
@Column(name = "ORDER_ID", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long orderId;
@Column(name = "CUSTOMER_ID")
@ManyToOne(optional=false)
@JoinColumn(name="CUSTOMER_ID",referencedColumnName="CUSTOMER_ID")
private long customerId;
@Column(name = "DATE_SHIPPED")
private Boolean dateShipped;
@Column(name = "ORDER_DATE")
private Date orderDate;
@Column(name = "STATUS")
private Date status;
}
现在,我定义了persistance.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="todos" transaction-type="RESOURCE_LOCAL">
<class>b.model.Customer</class>
<class>b.model.Order</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.url"
value="jdbc:derby://localhost:1527/baza;create=true" />
</properties>
</persistence-unit>
</persistence>
现在我被困在那个不知道如何初始化
EntityManager
实际读取我的persistance.xml
以连接到数据库并创建给定实体的地方。我尝试了以下方法:private static EntityManagerFactory factory;
public static void main(String[] args) {
factory = Persistence.createEntityManagerFactory(....);
EntityManager em = factory.createEntityManager();
}
但是说实话,我真的不知道
createEntityManagerFactor()
方法的构造函数应该包含什么内容。任何帮助都超过了欢迎!
最佳答案
您需要在创建persistance-unit
时指定EntityManagerFactory
名称:
factory = Persistence.createEntityManagerFactory("todos");
EntityManager em = factory.createEntityManager();