如何使Java JPA创建实体?

时间:2016-10-12 19:58:16

标签: java jpa

我正在学校项目,我需要使用JPA。我有一些这样的架构:

Customer.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()方法的构造函数中加入什么。

非常欢迎任何帮助!

1 个答案:

答案 0 :(得分:1)

在创建persistance-unit时,您需要指定EntityManagerFactory名称:

factory = Persistence.createEntityManagerFactory("todos");
EntityManager em = factory.createEntityManager();