hibernate cascade=CascadeType.All


 因為時間關系,我在這里測試的環境是一對多的關系里面用到的注解方式的級聯,網上也有很多貼子,我也看過了,但是呢,我還是自己總結一下吧,這覺得級聯是單向的,不是雙向的,意思就是說,我們在設置兩個類的對象之間關系的時候,總是在一方設置的很具體,在另外一方設置一個mappedBy即可,但是如果想要兩邊都能刪除的時候,或者在生成的時候,必須在兩邊都設置cascade=CascadeType.All才有效果,下面是測試代碼,測試樣例是參考馬士兵的視頻做的,

package com.jll.model;

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

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="t_group")
public class Group {
    private int id;
    private String name;
    private Set<User> users = new HashSet<User>();

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @OneToMany(mappedBy="group",cascade=CascadeType.ALL)
    public Set<User> getUsers() {
        return users;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setUsers(Set<User> users) {
        this.users = users;
    }

}

現在這里有cascade=CascadeType.ALL。在相關聯的類的另一邊同樣也有,

package com.jll.model;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name = "t_user")
public class User {
    private int id;
    private String name;
    private Group group;

    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="groupId")
    public Group getGroup() {
        return group;
    }

    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public String toString(){
        return this.getName()+"---"+this.getId()+"---"+this.getGroup().getId();
    }

}

測試代碼:

package com.jll.model;

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

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

public class TestCoreAPI {
    
    private static SessionFactory sf=null;
    private static Configuration configuration = new Configuration().configure();
    
    @BeforeClass
    public static void beforeClass(){
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
        applySettings(configuration.getProperties());
        sf = configuration.buildSessionFactory(builder.build());
    }
    
    @AfterClass
    public static void afterClass(){
        sf.close();
    }
@Test
    public void testRelationShip(){
        SchemaExport se = new SchemaExport(configuration);
        se.create(true, true);
        Session session  = sf.getCurrentSession();
        Group g = new Group();
        g.setName("group1");
        User u1 = new User();
        User u2 = new User();
        /*u1.setGroup(g);
        u2.setGroup(g);*/
        u1.setName("u1");
        u2.setName("u2");
        Set<User> users = new HashSet<User>();
        users.add(u1);
        users.add(u2);
        g.setUsers(users);
        session.beginTransaction();
        session.save(g);
        session.getTransaction().commit();
    }

生成的SQL語句如下:

alter table t_user 
        drop 
        foreign key FK_7ktm6l2qkykpqrf6oq01ys8wy

    drop table if exists t_group

    drop table if exists t_user

    create table t_group (
        id integer not null auto_increment,
        name varchar(255),
        primary key (id)
    )

    create table t_user (
        id integer not null auto_increment,
        name varchar(255),
        groupId integer,
        primary key (id)
    )

    alter table t_user 
        add constraint FK_7ktm6l2qkykpqrf6oq01ys8wy 
        foreign key (groupId) 
        references t_group (id)
Hibernate: 
    insert 
    into
        t_group
        (name) 
    values
        (?)
Hibernate: 
    insert 
    into
        t_user
        (groupId, name) 
    values
        (?, ?)
Hibernate: 
    insert 
    into
        t_user
        (groupId, name) 
    values
        (?, ?)

如果Group類沒有加上級聯的話,生成的語句如下:

alter table t_user 
        drop 
        foreign key FK_7ktm6l2qkykpqrf6oq01ys8wy

    drop table if exists t_group

    drop table if exists t_user

    create table t_group (
        id integer not null auto_increment,
        name varchar(255),
        primary key (id)
    )

    create table t_user (
        id integer not null auto_increment,
        name varchar(255),
        groupId integer,
        primary key (id)
    )

    alter table t_user 
        add constraint FK_7ktm6l2qkykpqrf6oq01ys8wy 
        foreign key (groupId) 
        references t_group (id)
Hibernate: 
    insert 
    into
        t_group
        (name) 
    values
        (?)

這里只插入了一次,而上面的那個插入了三次,所以我猜測級聯是單向的,不是雙向的,如果想要兩邊都可以進行crud,則被關聯的類都要加上cascade=CascadeType.ALL,我也進行了刪除測試,刪除的時候必須先查出來,然后才能進行級聯刪除,得出來的結論也是與上面的實驗一樣,在這里就不貼代碼了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM