配置:
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/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"> <persistence-unit name="JPA" transaction-type="RESOURCE_LOCAL"> <!-- 配置用什么orm 产品作为jpa的实现 --> <!-- 1.实际上配置的是 javax.persistence.spi.PersistenceProvider接口的实现类 2.若只有一个jpa的实现,也可以比配置该节点 --> <provider>org.hibernate.ejb.HibernatePersistence</provider> <!-- 添加持久化类 --> <class>entity.Customer</class> <class>entity.Order</class> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql:///jpa" /> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <property name="javax.persistence.jdbc.user" value="root" /> <property name="javax.persistence.jdbc.password" value="manager123" /> <!-- 配置jpa的实现产品的基本属性,配置hibernate的基本属性 --> <property name="hibernate.format_sql" value="true" /> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="update" /> </properties> </persistence-unit> </persistence>
entity customer
package entity; import java.util.ArrayList; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.CascadeType; 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.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.eclipse.persistence.jpa.config.Cascade; @Table(name = "customer") @Entity public class Customer { private int id; private String lastName; private String email; private int age; private Date birthday; private Date creatTime; /******** 一对多关系, 一个顾客,有多个订单 ********/ Set<Order> orders = new HashSet<Order>(); @JoinColumn(name = "CUSTOMER_ID") // 用来映射外键列的名称 //cascade={CascadeType.REMOVE} 设置级联删除 //mappedBy="customer" 设置谁来维护关系爱 (在此设置多的 customer维护,及Customer不维护,有order维护) //!!!使用mappedBy="XX“属性,@JoinColumn(name="XXXX")不用指定(否则会报错) @OneToMany(fetch=FetchType.EAGER,cascade={CascadeType.REMOVE},mappedBy="customer") // 映射一对多的关系 public Set<Order> getOrders() { return orders; } public void setOrders(Set<Order> orders) { this.orders = orders; } /*************** 使用table生成主键的策略 *******************************/ // @TableGenerator(name="ID_GENARATER", // table="jpa_id_generators", // pkColumnName="PK_NAME", //指定主键键的列 // pkColumnValue="CUSTOMER_ID", //指定主键的行(列的哪一行) // valueColumnName="PK_VALUE", //指定主键值的列 // allocationSize=100) //主键增加的大小,默认为50 // @GeneratedValue(strategy=GenerationType.TABLE,generator="ID_GENARATER") // //generator与@TableGenerator的name对应 /************************************/ @GeneratedValue(strategy = GenerationType.AUTO) @Id public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name = "last_name") public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Temporal(TemporalType.DATE) public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Temporal(TemporalType.TIMESTAMP) public Date getCreatTime() { return creatTime; } public void setCreatTime(Date creatTime) { this.creatTime = creatTime; } @Override public String toString() { return "Customer [id=" + id + ", lastName=" + lastName + ", email=" + email + ", age=" + age + ", birthday=" + birthday + ", creatTime=" + creatTime + "]"; } }
Order
package entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Table(name="JPA_ORDERS") @Entity public class Order { private Integer id; private String orderName; // private Customer customer; //暂时注掉。测试一对多 @GeneratedValue @Id public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="ORDER_NAME") public String getOrderName() { return orderName; } public void setOrderName(String orderName) { this.orderName = orderName; } /** * @JoinColumn //映射外键 * @ManyToOne //映射一对多的关系 * ***/ // @JoinColumn(name="CUSTOMER_ID") // @ManyToOne(fetch=FetchType.LAZY) // public Customer getCustomer() { // return customer; // } // // public void setCustomer(Customer customer) { // this.customer = customer; // } }
manyToOneTest
package test; import java.util.Date; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import org.junit.After; import org.junit.Before; import org.junit.Test; import entity.Customer; import entity.Order; public class japManyToOneTest { private EntityManagerFactory entityManagerFactory; private EntityManager entityManager; private EntityTransaction entityTransaction; @Before public void init() { entityManagerFactory = Persistence.createEntityManagerFactory("JPA"); entityManager = entityManagerFactory.createEntityManager(); entityTransaction = entityManager.getTransaction(); entityTransaction.begin(); } @After public void distory() { entityTransaction.commit(); entityManager.close(); entityManagerFactory.close(); } /* (多对一测试,由于测试一对一多,把Order中的Customer注释了) @Test public void testManyToOneUpdate() { Order order = entityManager.find(Order.class, 6); order.getCustomer().setLastName("MM"); } //* 不能删除1的一方,由于有外键关联 @Test public void testManyToOneDelete() { Order order = entityManager.find(Order.class, 5); entityManager.remove(order); // Customer customer = entityManager.find(Customer.class, 4); // entityManager.remove(customer); } //* default user left out select we cen user the parameter of fecth="lazy" // * at @manytoOne(fecth="lazy") @Test public void testManyToOneFind() { Order order = entityManager.find(Order.class, 5); System.out.println(order); System.out.println(order.getCustomer().getLastName()); } // * 对于多对一,建议先保存1的一端,然后保存多的一端。 (这样就不会多出额外的update语句) 及让多的一方维护关系 @Test public void ManyToOnePersistence() { Customer customer = new Customer(); customer.setAge(23); customer.setEmail("qq@163.com"); customer.setLastName("QQ"); customer.setBirthday(new Date()); customer.setCreatTime(new Date()); Order order1 = new Order(); order1.setOrderName("OO_order_01"); Order order2 = new Order(); order2.setOrderName("OO_order_02"); // 设置关联关系 order1.setCustomer(customer); order2.setCustomer(customer); // 保存 entityManager.persist(customer); entityManager.persist(order1); entityManager.persist(order2); } */ }
oneToManyTest
package test; import static org.junit.Assert.*; import java.util.Date; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import org.junit.After; import org.junit.Before; import org.junit.Test; import entity.Customer; import entity.Order; public class japOneToManyTest { private EntityManagerFactory entityManagerFactory; private EntityManager entityManager; private EntityTransaction entityTransaction; @Before public void init() { entityManagerFactory = Persistence.createEntityManagerFactory("JPA"); entityManager = entityManagerFactory.createEntityManager(); entityTransaction = entityManager.getTransaction(); entityTransaction.begin(); } @After public void distory() { entityTransaction.commit(); entityManager.close(); entityManagerFactory.close(); } @Test public void testOneToMany(){ Customer customer = entityManager.find(Customer.class, 15) ; Set<Order> orders = customer.getOrders(); Order order = orders.iterator().next(); order.setOrderName("AAAAAAAAAAAAAAAA"); //System.out.println(order); } /** * 一对多,默认删除一的一方,多的一方外键会置空,一的一方会被删除,多的一方保留,外键置空 * 可以通过级联删除一并删除(在@onetomany(cascade={CascadeType.REMOVE})) */ @Test public void testOneToManyDelete(){ Customer customer = entityManager.find(Customer.class, 12); entityManager.remove(customer); } /** * default staregt is lazy 默认关联多的一方使用lazy加载策略 * @throws Exception */ @Test public void testOneToManyFind() throws Exception { Customer customer = entityManager.find(Customer.class, 2); System.out.println(customer.getLastName()); //获取一对多的多。 default staregt is lazy System.out.println(customer.getOrders().size()); } /** * 对于一对多, 保存时,无论是先保存一的一端,还是多的一端都会执行update语句 * 因为多的一端 ,在保存时不会同时插入外键列 */ @Test public void testOneToManyPersistence(){ Customer customer = new Customer(); customer.setAge(23); customer.setEmail("KKKK@163.com"); customer.setLastName("KKKK"); customer.setBirthday(new Date()); customer.setCreatTime(new Date()); Order order1 = new Order(); order1.setOrderName("DDDD_01"); Order order2 = new Order(); order2.setOrderName("DDDD_02"); //建立关系 customer.getOrders().add(order1); customer.getOrders().add(order2); //执行保存 entityManager.persist(customer); entityManager.persist(order1); entityManager.persist(order2); } }