[Hibernate] One-To-Many 配置文件和注解的方式以及HQL语句

  一对多需要在一的类配置多的类的set泛型集合.

  多的一端需要添加一的类作为属性,其和数据库对应的是对应表的主键.

一个购物车有多个商品,购物车有个cart_id作为主键,商品除了自己的items_id作为主键外,还有一个cart_id作为外键.

需要在Cart类中声明一个Set<Item> items,在Items类中声明一个Cart cart属性.

在配置文件Cart.hbm.xml中配置

set>name=集合名 table=表名

key>column> name=外键

one-to-many> class=类名

在items.hbm.xml中配置

添加处理:

public static void main(String[] args) {

        Cart cart = new Cart();
        cart.setName("MyCart");
        
        Items item1 = new Items("I1", 10, 1, cart);
        Items item2 = new Items("I2", 20, 2, cart);
        Set<Items> itemsSet = new HashSet<Items>();
        itemsSet.add(item1); itemsSet.add(item2);
        
        cart.setItems(itemsSet);
        cart.setTotal(10*1 + 20*2);
        
        SessionFactory sessionFactory = null;
        Session session = null;
        Transaction tx = null;
        try{
        //Get Session
        sessionFactory = HibernateUtil.getSessionFactory();
        session = sessionFactory.getCurrentSession();
        System.out.println("Session created");
        //start transaction
        tx = session.beginTransaction();
        
        //Save the Model objects
        session.save(cart);
        session.save(item1);
        session.save(item2);

        tx.commit();
        if(!sessionFactory.isClosed()){
            sessionFactory.close();
        }}}

因为Cart实体类中没有声明构造函数,所以只能通过默认构造函数Cart cart=new Cart();

然后set属性来实现增加Cart对象.

其中set属性的顺序只要在save在save之前即可.记得要cart.setItems(itemsSet);one-to-many;

但是不需要items.setCart(cart);//自动指定?但为什么cart需要set?

需要同时save cart和item1,item2.

然后提交.

虽然item的主键和外键都没有指定,但其主键在配置文件中如:

所以实现了自增.

hibernate帮助将其外键对应的cart_id添加到外键column上.

 ===============

注解方法则是需要在id上注解@Id和@GeneratedValue(strategy=GenerationType.策略)

在Set<Items1> items1上注解@OneToMany(mappedBy="cart1")

Items1对应的有:

==========

此外配置文件中,配置文件方法的mapping是

        <mapping resource="cart.hbm.xml"/>

注解方法是:

<mapping class="com.journaldev.hibernate.model.Cart1"/>

=============

附录:服务器配置:

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatedb</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

----------------------------

<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:orcl</property>
<property name="connection.username">scott</property>
<property name="connection.password">orcl</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>

=======================HQL=======================

宛如智障,暗藏锋芒
原文地址:https://www.cnblogs.com/zienzir/p/9235999.html