继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Hibernate双向一对多关联映射demo--以user和order为例

我有一双明亮的眼睛
关注TA
已关注
手记 13
粉丝 19
获赞 269

1.新建工程(由于的双向一对多关联映射,所以在Users.java文件中和Orders.java文件中都存在彼此之间的关联),通过user.hbm.xml和orders.hbm.xml实现java类和数据库的映射关系,使用<many-to-one><one-to-many>实现关系配置

思考:一个user可以有多个order,一个order只能有一个user, 可以通过user找到属于它的所有order,可以通过order找到它的唯一的user.所以user to order 是:<one-to-many>的映射,order to user 是<many-to-one>的映射。

工程目录如下:
注:需要导入hibernate和mysql.jar包
图片描述

在数据库工具中新建表orders
图片描述

新建表users
图片描述

2.准备工作完成,然后编写java类和.xml文件

/*************Users.java*********************/
package com.feng.dao;

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

public class Users {

    private Integer userId;
    private String userName;
    private Set<Orders> orders =new HashSet<Orders>(0); //one to many

    public Integer getUserId() {
        return userId;
    }
    public void setUserId(Integer userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    public Set<Orders> getOrders() {
        return orders;
    }
    public void setOrders(Set<Orders> orders) {
        this.orders = orders;
    }
}
/*************Orders.java*********************/
package com.feng.dao;

public class Orders {
    private Integer orderId;
    private String orderPrize;

    private Users user ; //mang to one 

    public Integer getOrderId() {
        return orderId;
    }

    public void setOrderId(Integer orderId) {
        this.orderId = orderId;
    }

    public String getOrderPrize() {
        return orderPrize;
    }

    public void setOrderPrize(String orderPrize) {
        this.orderPrize = orderPrize;
    }

    public Users getUser() {
        return user;
    }

    public void setUser(Users user) {
        this.user = user;
    }
}

hibernate.cfg.xml

<!-- ~ Hibernate, Relational Persistence for Idiomatic Java ~ ~ License: 
    GNU Lesser General Public License (LGPL), version 2.1 or later. ~ See the 
    lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. -->
<!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>
        <!--mysql database -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/student</property>
        <!-- student is your database. -->
        <property name="connection.username">root</property> 
        <!-- Account is root.  -->
        <property name="connection.password"></property>
        <!-- Password is null. -->
        <property name="connection.characterEncoding">utf8</property>
        <!-- Encoding is utf8. -->
        <property name="connection.pool_siez">10</property>
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>
        <!-- This represents the connection to the database.-->
        <mapping resource="com/feng/dao/users.hbm.xml" />
        <mapping resource="com/feng/dao/orders.hbm.xml" />
    </session-factory>
</hibernate-configuration>

users.hbm.xml

<?xml version='1.0' encoding='UTF-8'?> 
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.feng.dao">
    <class name="Users" table="users">
        <!-- name is the java's Attributes and the column is the table's -->
        <id name="userId" type="java.lang.Integer" column="userId">
            <generator class="increment" /><!-- incremental -->
        </id>
        <!-- all级联效果 -->
        <property name="userName" column="userName" />
        <set name="orders" cascade="all">
            <key column="userid"></key>
            <one-to-many class="Orders"></one-to-many>
        </set>
    </class>
</hibernate-mapping>

orders.hbm.xml

<?xml version='1.0' encoding='UTF-8'?> 
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.feng.dao">
    <class name="Orders" table="orders">
        <!-- name is the java's Attributes and the column is the table's  -->
        <id name="orderId" type="java.lang.Integer" column="orderId" >
            <generator class="increment" /><!-- incremental -->
        </id>
        <property name="orderPrize"  column="orderPrize" />
        <many-to-one name="user" class="Users" column="userId"></many-to-one>
    </class>
</hibernate-mapping>

Test.java

package com.feng.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import com.feng.dao.Orders;
import com.feng.dao.Users;

public class Test {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        // 1.进行配置文件的读取
        StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder();
        StandardServiceRegistry sr = ssrb.configure().build();
        // 2.由config得到一个会话工厂//得到sessionFactory
        SessionFactory sf = new MetadataSources(sr).buildMetadata().buildSessionFactory();
        // 3.由sessionFacatory得到session
        Session session = sf.openSession();
        /*
         * 开启事务,增删改都需要事务
         */
        Transaction tran = session.beginTransaction(); // 不但得到事务的对象而且还开启了,,还可以session.getTransaction().begin();
        //增加绑定order的用户
        // Users u1 = new Users();
        // u1.setUserName("zhangsan");
        // Orders o1 = new Orders();
        // o1.setOrderPrize("99");
        // o1.setUser(u1);
        // Orders o2 = new Orders();
        // o2.setOrderPrize("22");
        // o2.setUser(u1);
        // u1.getOrders().add(o1);
        // u1.getOrders().add(o2);
        // session.save(u1);

        //修改属性值
         Users u =session.get(Users.class, 1); //这里的1表示的是id号
         u.setUserName("wwuuuwww");
         Orders o =u.getOrders().iterator().next();
         o.setOrderPrize("73000");
         session.update(u);

        tran.commit(); // 一定要提交事务!!!!!!!
        // 4.记得关闭session
        session.close();
        sf.close();

    }
}

结果描述:
图片描述
图片描述

hibernate刚开始练习,比较容易出现错误,hibernate比较适合中大型项目,因为hibernate的配置比较繁琐,但是配置成功后就会降低了编码的复杂度。

生命不息,代码不止,加油!!!!!!
打开App,阅读手记
3人推荐
发表评论
随时随地看视频慕课网APP

热门评论

一开始添加的两个order的价格分别是22和99,最后随机修改了某个为73000,3000怎么来的..

会提示找不到对应的实体类是怎么回事?

查看全部评论