完整测试项目可在这里下载:http://download.csdn.net/detail/liangrui1988/6542729
部分代码:
META-INF
persistence.xml
<?xml version="1.0" encoding="UTF-8"?> <persistence 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_1_0.xsd" version="1.0"> <persistence-unit name="rui" transaction-type="RESOURCE_LOCAL"> <!-- 全局事务配置 <jta-data-source>java:/DefaultDS</jta-data-source> --> <properties> <!-- hibernate config org.hibernate.dialect.HSQLDialect org.hibernate.dialect.MySQLDialect --> <property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect"/> <property name="hibernate.hbm2ddl.auto" value="update"/> <property name="show_sql" value="true"/> <!-- database config --> <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/> <property name="hibernate.connection.username" value="juxun"/> <property name="hibernate.connection.password" value="rui"/> <property name="hibernate.connection.url" value="jdbc:oracle:thin:@127.0.0.1:1521:ABC"/> <!-- <property name="hibernate.max_fetch_depth" value="3"/> --> </properties> </persistence-unit> </persistence>
ManyToMany
package com.rui.ManyToMany; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @Entity @GenericGenerator(name = "stuId", strategy = "sequence",parameters=@Parameter(name="sequence",value="preson_id")) public class Student { private Integer id; private String name; private Set<Teacher> teacher=new HashSet<Teacher>(); @Id @GeneratedValue(generator="stuId") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToMany(cascade={CascadeType.REFRESH}) //@JoinTable(name="stu_tea") @JoinTable(name="stu_tea",inverseJoinColumns=@JoinColumn(name="tea_id") ,joinColumns=@JoinColumn(name="stu_id")) public Set<Teacher> getTeacher() { return teacher; } public void setTeacher(Set<Teacher> teacher) { this.teacher = teacher; } //添加学生和老师的关系 public void addTeacher(Teacher te){ this.teacher.add(te); } //解除学生跟老师的关系 public void removeTeacher(Teacher te){ if(this.teacher.contains(te)){ this.teacher.remove(te); } } }
package com.rui.ManyToMany; import java.util.HashSet; 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.Id; import javax.persistence.ManyToMany; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @Entity @GenericGenerator(name = "teaId", strategy = "sequence",parameters=@Parameter(name="sequence",value="preson_id")) public class Teacher { private Integer id; private String name; private Set<Student> student=new HashSet<Student>(); @Id @GeneratedValue(generator="teaId") public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(length=10,nullable=false) public String getName() { return name; } public void setName(String name) { this.name = name; } //被维护端 mappedBy (Teacher)老师被学生维护 (Student) @ManyToMany(cascade={CascadeType.REFRESH},mappedBy="teacher") public Set<Student> getStudent() { return student; } public void setStudent(Set<Student> student) { this.student = student; } //为hash分区 @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Teacher other = (Teacher) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } }
package com.rui.ManyToMany; import static org.junit.Assert.*; import java.util.HashSet; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.junit.Test; import com.rui.ManyToOne.Order; import com.rui.ManyToOne.OrderItem; public class ManyToManyTest { @Test public void test() { EntityManagerFactory emf=Persistence.createEntityManagerFactory("rui"); EntityManager em= emf.createEntityManager(); em.getTransaction().begin(); Teacher te=new Teacher(); te.setName("刘老师"); Teacher te2=new Teacher(); te.setName("李老师"); em.persist(te); //给学生分两个老师 Student stu=new Student(); stu.setName("小明"); //stu.getTeacher().add(te);//学生加老师 //stu.getTeacher().add(te2); em.persist(stu);//保存学生 em.getTransaction().commit(); em.close(); emf.close(); System.out.println("ok...."); } /** * 建立关系 */ @Test public void addRe(){ EntityManagerFactory emf=Persistence.createEntityManagerFactory("rui"); EntityManager em= emf.createEntityManager(); em.getTransaction().begin(); Student st=em.find(Student.class,46);//获取一个学生 //刷新对象 获得老师 并建立关系 st.addTeacher(em.getReference(Teacher.class,47)); em.getTransaction().commit(); em.close(); emf.close(); System.out.println("ok...."); } /** * 删除关系 */ @Test public void removeRe(){ EntityManagerFactory emf=Persistence.createEntityManagerFactory("rui"); EntityManager em= emf.createEntityManager(); em.getTransaction().begin(); Student st=em.find(Student.class,46);//获取一个学生 st.removeTeacher(em.getReference(Teacher.class,45));//刷新对象 并建立关系 em.getTransaction().commit(); em.close(); emf.close(); System.out.println("ok...."); } /** * 删除老师 */ @Test public void deleteTeacher(){ EntityManagerFactory emf=Persistence.createEntityManagerFactory("rui"); EntityManager em= emf.createEntityManager(); em.getTransaction().begin(); //先解除关系才能删除老师 Student st=em.find(Student.class,46);//获取一个学生 st.removeTeacher(em.getReference(Teacher.class,45)); //删除老师 em.remove(em.getReference(Teacher.class,45)); em.getTransaction().commit(); em.close(); emf.close(); System.out.println("ok...."); } /** * 删除学生 */ @Test public void deleteStudent(){ EntityManagerFactory emf=Persistence.createEntityManagerFactory("rui"); EntityManager em= emf.createEntityManager(); em.getTransaction().begin(); Student st=em.find(Student.class,46);//获取一个学生 //删除 学生 关系维护端 有权利操作外健 em.remove(st); em.getTransaction().commit(); em.close(); emf.close(); System.out.println("ok...."); } }
ManyToOne
==========================================
package com.rui.ManyToOne; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; @Entity public class OrderItem { private Integer id; private String productName;//产品名称 private Float sellPrice;//销售价格 private Order order;//订单 @Id //@Column(name="ids",length=8) public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public Float getSellPrice() { return sellPrice; } public void setSellPrice(Float sellPrice) { this.sellPrice = sellPrice; } //optional =true 可选 ,存放的值可以为null(外健) @ManyToOne(cascade={CascadeType.REFRESH,CascadeType.MERGE} ,optional=false) @JoinColumn(name="order_id") //关联字段 外健id public Order getOrder() { return order; } public void setOrder(Order order) { this.order = order; } }
package com.rui.ManyToOne; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name="orders") public class Order { private String orderId; private Float amount; private Set<OrderItem> item=new HashSet<OrderItem>(); @Id @Column(name="order_id",length=8) public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } @Column(nullable=false) public Float getAmount() { return amount; } public void setAmount(Float amount) { this.amount = amount; } /** * alter table OrderItem * add constraint pk_order foreign key order * reference order(orderId) * 一个订单对应多个订单项 * 多个订单项对应一个订单 * @return */ //那个类出现了mappedBy 就是关系被维护端 //order 指定这个属性来维据关系 @OneToMany(cascade={CascadeType.REFRESH,CascadeType.PERSIST,CascadeType.MERGE,CascadeType.REMOVE} ,fetch=FetchType.LAZY,mappedBy="order") public Set<OrderItem> getItem() { return item; } public void setItem(Set<OrderItem> item) { this.item = item; } public void addOrderItem(OrderItem oi){ oi.setOrder(this);//送来的订单项对象里加入 订单 this.item.add(oi);//添加订单 里的订单项 } }
package com.rui.ManyToOne; import static org.junit.Assert.*; import java.util.UUID; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import org.junit.Test; public class OneToManyTest { @Test public void test() { EntityManagerFactory emf=Persistence.createEntityManagerFactory("rui"); EntityManager em= emf.createEntityManager(); em.getTransaction().begin(); Order order=new Order(); order.setOrderId("888");//UUID.randomUUID().toString() order.setAmount(90F); OrderItem oi=new OrderItem(); oi.setId(20); oi.setProductName("ipone"); oi.setSellPrice(5888F); //oi.setOrder(order); OrderItem oi2=new OrderItem(); oi2.setId(21); oi2.setProductName("ipone6"); oi2.setSellPrice(6888F); //订单里加入订单项 order.addOrderItem(oi); order.addOrderItem(oi2); //插入订单 em.persist(order); em.getTransaction().commit(); emf.close(); System.out.println("ok...."); } }
==================
复合主健
package com.rui.compositePK; import javax.persistence.EmbeddedId; import javax.persistence.Entity; @Entity public class AriLine { private AriLinePK id;//这里把复合主健看成一个整体 用一个类来描述它 private String name; public AriLine(){} public AriLine(String stratCity,String endCity,String name){ this.id=new AriLinePK(stratCity,endCity); this.name=name; } @EmbeddedId //可嵌入的类 id public AriLinePK getId() { return id; } public void setId(AriLinePK id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }