Hibernate注解-多对一关系映射注解,一对多关系映射注解,多对多关系映射注解

  • 多对一注解

    把多对一改成用注解来实现
    1. 把Category的id和name字段改为支持注解
    注: 分类的getName上并没有加上@Column(name="name"),也可以达到映射的效果。 因为getName方法默认会被认为是字段映射。 除非加上了@Transient 才表示不进行映射
    2. 把Product的getCategory进行多对一映射
      @ManyToOne
        @JoinColumn(name="cid") 
        public Category getCategory() {
            return category;
        }
    @ManyToOne 表示多对一关系
    @JoinColumn(name="cid") 表示关系字段是cid
    对比xml中的映射方式:
    3. 为hibernate.cfg.xml 添加Category的映射
    
    
    4. 运行TestHibernate

    import javax.persistence.Column;
     
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;
     
    @Entity
    @Table(name = "category_")
    public class Category {
        int id;
        String name;
         
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id")
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
         
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
     
    }
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    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 = "product_")
    public class Product {
        int id;
        String name;
        float price;
         
        Category category;
     
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id")  
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        @Column(name = "name")
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        @Column(name = "price")
        public float getPrice() {
            return price;
        }
        public void setPrice(float price) {
            this.price = price;
        }
     
        @ManyToOne
        @JoinColumn(name="cid")
        public Category getCategory() {
            return category;
        }
        public void setCategory(Category category) {
            this.category = category;
        }
    }
    
    
       
    
       
        
            
            com.mysql.jdbc.Driver
            jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
            utf-8
            root
            admin
            
            org.hibernate.dialect.MySQLDialect
            thread
            true
            update
    
            
            
      
        
       
    
  • 一对多注解

    在上一步的基础上做如下改动
    1. 为Category再加product集合,并提供getter和setter
    Set products;
        public Set getProducts() {
            return products;
        }
        public void setProducts(Set products) {
            this.products = products;
        }
    2. 给getProducts方法加上一对多注解
    @OneToMany(fetch=FetchType.EAGER)
        @JoinColumn(name="cid") 
        public Set getProducts() {
            return products;
        }
    @OneToMany 表示一对多,fetch=FetchType.EAGER 表示不进行延迟加载(FetchType.LAZY表示要进行延迟加载)
    @JoinColumn(name="cid") 表示映射字段
    对比xml中的映射方式:
      
                
                
            
    3. 修改TestHibernate为
      SessionFactory sf = new Configuration().configure().buildSessionFactory();
            Session s = sf.openSession();
            s.beginTransaction();
            Category c = (Category) s.get(Category.class, 1);
            s.getTransaction().commit();
            s.close();
            sf.close();
            Set ps = c.getProducts();
            for (Product p : ps) {
                System.out.println(p.getName());
            }
    import java.util.Set;
     
    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;
     
    @Entity
    @Table(name = "category_")
    public class Category {
        int id;
        String name;
        Set products;
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id")
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
         
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
         
        @OneToMany(fetch=FetchType.EAGER)
        @JoinColumn(name="cid")
        public Set getProducts() {
            return products;
        }
        public void setProducts(Set products) {
            this.products = products;
        }
    }
    import java.util.Set;
     
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
     
    import com.how2java.pojo.Category;
    import com.how2java.pojo.Product;
      
    public class TestHibernate {
        public static void main(String[] args) {
            SessionFactory sf = new Configuration().configure().buildSessionFactory();
            Session s = sf.openSession();
            s.beginTransaction();
            Category c = (Category) s.get(Category.class, 1);
            s.getTransaction().commit();
            s.close();
            sf.close();
            Set ps = c.getProducts();
            for (Product p : ps) {
                System.out.println(p.getName());
            }
        }
    }
  • 多对多注解

    1. 在基于XML配置的多对多知识点的基础上进行多对多注解的修改
    2.像上两步那样,为Product,User,Category 加上类和属性注解
    3. 加上多对一注解ManyToOne
    4. 加上一对多注解OneToMany

    5. ManyToMany
    为Product的getUsers加上
     @ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
        @JoinTable(
                name="user_product",
                joinColumns=@JoinColumn(name="pid"),
                inverseJoinColumns=@JoinColumn(name="uid")
        )    
        public Set getUsers() {
            return users;
        }
    对比Product.hbm.xml中的配置:
       
                
                
              


    为User的getProducts加上
      @ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
        @JoinTable(
                name="user_product",
                joinColumns=@JoinColumn(name="uid"),
                inverseJoinColumns=@JoinColumn(name="pid")
        )    
        public Set getProducts() {
            return products;
        }
    对比User.hbm.xml中的配置
      
                
                
               

    6. hibernate.cfg.xml
     
            
            
    7. 运行TestHibernate
    import java.util.Set;
     
    import javax.persistence.CascadeType;
    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.JoinTable;
    import javax.persistence.ManyToMany;
    import javax.persistence.Table;
      
    @Entity
    @Table(name="user_")
    public class User {
      
        int id;
        String name;
        Set products;
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        @ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
        @JoinTable(
                name="user_product",
                joinColumns=@JoinColumn(name="uid"),
                inverseJoinColumns=@JoinColumn(name="pid")
        )   
        public Set getProducts() {
            return products;
        }
        public void setProducts(Set products) {
            this.products = products;
        }
    }
    import java.util.Set;
     
    import javax.persistence.CascadeType;
    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.JoinTable;
    import javax.persistence.ManyToMany;
    import javax.persistence.ManyToOne;
    import javax.persistence.Table;
      
    @Entity
    @Table(name="product_")
    public class Product {
        int id;
        String name;
        float price;
        Category category;
        Set users;
      
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
         
        @ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
        @JoinTable(
                name="user_product",
                joinColumns=@JoinColumn(name="pid"),
                inverseJoinColumns=@JoinColumn(name="uid")
        )   
        public Set getUsers() {
            return users;
        }
        public void setUsers(Set users) {
            this.users = users;
        }
         
        @ManyToOne
        @JoinColumn(name="cid")    
        public Category getCategory() {
            return category;
        }
        public void setCategory(Category category) {
            this.category = category;
        }
         
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public float getPrice() {
            return price;
        }
        public void setPrice(float price) {
            this.price = price;
        }
          
    }
    import java.util.Set;
     
    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;
      
    @Entity
    @Table(name="category_")
    public class Category {
        int id;
        String name;
        Set products;
         
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
     
        @OneToMany(fetch=FetchType.EAGER)
        @JoinColumn(name="cid")    
        public Set getProducts() {
            return products;
        }
        public void setProducts(Set products) {
            this.products = products;
        }
    }
    import java.util.HashSet;
    import java.util.Set;
      
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;
      
    import com.how2java.pojo.Product;
    import com.how2java.pojo.User;
       
    public class TestHibernate {
        public static void main(String[] args) {
            SessionFactory sf = new Configuration().configure().buildSessionFactory();
       
            Session s = sf.openSession();
            s.beginTransaction();
              
    //        //增加3个用户
            Set users = new HashSet();
            for (int i = 0; i < 3; i++) {
                User u =new User();
                u.setName("user"+i);
                users.add(u);
                s.save(u);
            }
              
            //产品1被用户1,2,3购买
            Product p1 = (Product) s.get(Product.class, 1);
     
            p1.setUsers(users);
            s.getTransaction().commit();
            s.close();
            sf.close();
        }
    }
    
    
      
    
      
        
            
            com.mysql.jdbc.Driver
            jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8
            utf-8
            root
            admin
            
            org.hibernate.dialect.MySQLDialect
            thread
            true
            update
     
            
            
            
     
        
      
    


你可能感兴趣的:(框架-Hibernate)