Hibernate的注解配置

hibernate的注解配置 hibernate的注解配置和配置文件配置不同的是不需要在配置xxx.hbm.xml了
这里首先讲注解的配置,依着客户和订单的例子来讲解。(这里是一对多的关系,所以需要配置onetomany和manytoone)
客户的注解配置(一的一方)

package onetomany; import java.util.HashSet; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; @Entity @Table(name="t_customer") public class Customer { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private String name; @OneToMany(targetEntity=Order.class,mappedBy="c") @Cascade(CascadeType.ALL) private Setorders=new HashSet(); public Set getOrders() { return orders; } public void setOrders(Set orders) { this.orders = orders; } 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; } }

订单的注解配置(多的一方)
package onetomany; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="t_order") public class Order { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Integer id; private Double price; private String address; @ManyToOne(targetEntity=Customer.class) @JoinColumn(name="customer_id")//制定外键列 private Customer c; public Customer getC() { return c; } public void setC(Customer c) { this.c = c; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }

测试代码
package onetomany; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.junit.Test; public class test { @Test public void test1(){ Configuration configuration=new Configuration().configure(); SessionFactory factory=configuration.buildSessionFactory(); Session session=factory.openSession(); session.beginTransaction(); Customer c=new Customer(); c.setName("小红"); Order o1=new Order(); o1.setPrice(1000d); o1.setAddress("北京"); Order o2=new Order(); o2.setPrice(2000d); o2.setAddress("上海"); o1.setC(c); o2.setC(c); //为了进行级联操作 c.getOrders().add(o1); c.getOrders().add(o2); session.save(c); session.getTransaction().commit(); session.close(); } }

hibernate.cfg.xml的配置 【Hibernate的注解配置】这里和之前的配置文件有一点不同就是在映射的时候不是映射配置文件,而是映射到class里面去。
-factory> com.mysql.jdbc.Driver jdbc:mysql:///hibernate root 123456truetrueorg.hibernate.dialect.MySQLDialectupdate

    推荐阅读