持久层框架(Hibernate)

Posted Foreordination

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了持久层框架(Hibernate)相关的知识,希望对你有一定的参考价值。

一、Hibernate处理关系

关系主要有三种:1、多对一  2、一对多  3、多对多

1、多对一

一个Product对应一个Category,一个Category对应多个Product(一个产品对应一个类别,一个类别对应多个产品)

也就是Product和Category是多对一的关系。(多个产品对应一个类别)

1.1在数据test下创建表category_table,两个字段,id(自增),字符串格式name

其实也不用建表,因为Hibernate会自动建表。

技术分享图片
use test;
 
CREATE TABLE category_ table(
  id int(11) NOT NULL AUTO_INCREMENT,
  name varchar(30) ,
  PRIMARY KEY (id)
) DEFAULT CHARSET=UTF8;
View Code

1.2、准备类别实体类(Category.java)

技术分享图片
package com.demo.pojo
public class Category{
    private int id;//类别id
    private String name;//类别名称
    
    //属性的getter/setter方法
    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;
    }
}
View Code

1.3、准备类别实体类的映射xml(Category.hbm.xml)

技术分享图片
<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.how2java.pojo">
    <class name="Category" table="category_table">
        <id name="id" column="id">
            <generator class="native">
            </generator>
        </id>
        <property name="name" />
    </class>
    
</hibernate-mapping>
View Code

1.4、为产品实体类(Product.java)增加Category属性

技术分享图片
package com.how2java.pojo;
public class Product {
    int id;
    String name;
    float price;
        //增加Category的属性
    Category category;
    public Category getCategory() {
        return category;
    }
    public void setCategory(Category category) {
        this.category = category;
    }

    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;
    }
    public float getPrice() {
        return price;
    }
    public void setPrice(float price) {
        this.price = price;
    }
    
}
View Code

1.5、为产品映射xml文件(Product.hbm.xml)设置Category多对一关系

<many-to-one name="category" class="Category" column="cid" />

使用many-to-one标签设置多对一关系,name="category",对应Product类中的category属性

class="Category"表示对应Category类,column="cid"表示指向category_table的外键。

具体配置xml如下:

技术分享图片
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.how2java.pojo">
    <class name="Product" table="product_">
        <id name="id" column="id">
            <generator class="native">
            </generator>
        </id>

        <property name="name" />
        <property name="price" />
        <many-to-one name="category" class="Category" column="cid" />
    </class>
    
</hibernate-mapping>
View Code

1.6、在hibernate.cfg.xml中增加Category的映射文件

技术分享图片
<?xml version=‘1.0‘ encoding=‘utf-8‘?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test?characterEncoding=GBK</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <!--Product实体类的映射文件-->
        <mapping resource="com/demo/pojo/Product.hbm.xml" />
        <!--Category实体类的映射文件-->
        <mapping resource="com/demo/pojo/Category.hbm.xml" />
    </session-factory>

</hibernate-configuration>
View Code

1.7测试many-to-one多对一关系

技术分享图片
package com.demo.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.demo.pojo.Product;
public class TestHibernate{
    public static void main(String[] args){
        SessionFactory sf=new Configuration().configure().buildSessionFactory();
        Session session=sf.opneSession();
        session.beginTransaction();
        
        Category category=new Category();
        category.setName("car");
        session.save(category);
        
        Product product=(Product)s.get(Product.clas,5);//获取id=5的产品
        product.setCategory(category);//把类别设置到产品的实体类中
        session.update(p);
        
        session.getTransaction().commint();
        session.close();
        sf.close();
    }
}
View Code

 

2、一对多

Category和Product是一对多关系(一个Category对应多个Product)

2.1、给Category实体类增加一个Set集合(无序的Product)

技术分享图片
package com.demo.pojo
import java.util.Set;
public class Category{
    private int id;//类别id
    private String name;//类别名称
    
    //属性的getter/setter方法
    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;
    }
    
    //设置Product的Set
    Set<Product> products;
    public Set<Product> getProducts(){
        return products;
    }
    public void SetProducts(Set<Product> products){
        this.products=products;
    }
}
View Code

2.2、给Category.hbm.xml增加one-to-many映射

<set name="products" lazy="false">
    <key column="cid" not-null="false"/>
    <ont-to-many class="Product"/>
</set>

set标签用于设置一对多关系,也可以设置多对多。

name="products"对应Category类中的products属性,lazy="false",表示不使用延迟加载

<key colum="cid" not-null="false"/>表示外键是cid,可以为空

<one-to-many class="Product"/>表示一对多对应的类是Product

技术分享图片
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.how2java.pojo">
    <class name="Category" table="category_">
        <id name="id" column="id">
            <generator class="native">
            </generator>
        </id>
        <property name="name" />

        <!--set标签设置一对多关系-->
        <set name="products" lazy="false">
            <key column="cid" not-null="false" />
            <one-to-many class="Product" />
        </set>                
    </class>    
</hibernate-mapping>
View Code

2.3、测试one-to-many关系

  首先获取id=i的category,然后通过getProducts()获取所对应的所有的product

技术分享图片
package com.demo.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.demo.pojo.Product;
public class TestHibernate{
    public static void main(String[] args){
        SessionFactory sf=new Configuration().configure().buildSessionFactory();
        Session session=sf.opneSession();
        session.beginTransaction();
        
        Category category=new Category();
        category.setName("car");
        session.save(category);
        
        Category category=(Category)session.get(Category.class,1);//获取id=1的类别
        Set<Product> set=c.getProducts();//获取产品的集合
        for(Product p:set){//遍历产品集合
            System.out.println(p.getName());
        }
        session.getTransaction().commint();
        session.close();
        sf.close();
    }
}
View Code

 

3、多对多

一种product可以被多个User购买,一个User可以购买多种Product

所以Product和User之间关系是多对多many-to-many

要实现多对多关系,必须要有一张中间表,user_product用于维护User和Product之间的关系

3.1、User的实体类(User.java)

  增加Product集合

技术分享图片
package com.demo.pojo;
import java.util.Set;
public class User{
    private int id;//用户id
    private String name;//用户名
    Set<Product> products;//产品
    
    //属性的getter/setter方法
    public int getId(){
        return id;
    }
    public void setId(int id){
        this.id=id;
    }
    public int getName(){
        return name;
    }
    public void setName(String name){
        this.name=name;
    }
    //设置Product的Set
    public Set<Product> getProducts(){
        return products;
    }
    public void setProducts(Set<Product> products){
        this.products=products;
    }
}
View Code

3.2、User.hbm.xml映射文件xml的编写

技术分享图片
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.how2java.pojo">
    <class name="User" table="user_">
        <id name="id" column="id">
            <generator class="native">
            </generator>
        </id>
        <property name="name" />

                <!--配置Product与User的多对多关系,中间表是user_product-->
        <set name="products" table="user_product" lazy="false">
            <key column="uid" />
            <many-to-many column="pid" class="Product" />
        </set>                
    </class>    
</hibernate-mapping>
View Code

3.3、Product的实体类(Product.java)

  增加User的集合

技术分享图片
package com.demo.pojo;
import java.util.Set;
public class Product{
    private int id;
    private String name;
    private float price;
    
    Category category;//一对多
    
    Set<User> users;//多对多
    
    //属性的getter/setter方法
    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;
    }
    public float getPrice(){
        return price;
    }
    public void setPrice(float price){
        this.price=price;
    }
    
    //Category
    public Category getCategory(){
        return category;
    }
    public void setCategory(Category category){
        this.category=category;
    }
    //Set<User>
    public Set<User> getUser(){
        return users;
    }
    public vodi setUser(Set<User> users){
        this.users=users;
    }
}
View Code

3.4、Product的映射文件配置(Product.hbm.xml)

技术分享图片
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.how2java.pojo">
    <class name="Product" table="product_">
        <id name="id" column="id">
            <generator class="native">
            </generator>
        </id>
        <property name="name" />
        <property name="price" />
                <!--多对一-->
        <many-to-one name="category" class="Category" column="cid" />
        <!-- 多对多-->
        <set name="users" table="user_product" lazy="false">
            <key column="pid" />
            <many-to-many column="uid" class="User" />
        </set>                        
    </class>    
</hibernate-mapping>
View Code

3.5、在hibernate.cfg.xml中增加User.hbm.xml的映射

技术分享图片
<?xml version=‘1.0‘ encoding=‘utf-8‘?>
<!DOCTYPE hibernate-configuration PUBLIC
       "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/test?characterEncoding=GBK</property>
        <property name="connection.username">root</property>
        <property name="connection.password">admin</property>
        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">update</property>
        <!--映射文件的配置-->
        <mapping resource="com/demo/pojo/Product.hbm.xml" />
        <mapping resource="com/demo/pojo/Category.hbm.xml" />
        <mapping resource="com/demo/pojo/User.hbm.xml" />
    </session-factory>

</hibernate-configuration>
View Code

3.6、测试多对多many-to-many关系

技术分享图片
package com.demo.test;

import java.util.HashSet;
import java.util.Set;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.demo.pojo.Product;
import com.demo.pojo.User;

public class TestHibernate{
    public static void main(String[] args){
        SessionFactory sf=new Configuration().configure().buildSessionFactory();
        Session session=sf.opneSession();
        session.beginTransaction();
        //增加3个用户
        Set<User> users=new HashSet();
        for(int i=0;i<3;i++){
            User u=new User();
            u.setName("user"+i);
            users.add(u);
            s.save(u);
        }
        //id=1产品被用户1,2,3购买
        Product product=(Product)session.get(Product.class,1);
        product.setUsers(users);
        s.save(product);
        
        session.getTransaction().commint();
        session.close();
        sf.close();
    }
}
View Code

 

以上是关于持久层框架(Hibernate)的主要内容,如果未能解决你的问题,请参考以下文章

Hibernate: 数据持久层框架

持久层框架(Hibernate)

持久层框架--hibernate

Hibernate持久层ORM框架

持久层框架--hibernate

持久层框架(Hibernate)一