简体   繁体   中英

Get data in a many-to-many connection

I got a problem, with my hibernate database connection. At first I post some data:

Objects.java:

@Entity
@Table (name = "objects", schema="genmeta")
public class Objects {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int o_id;
    private String o_name;
    private String o_desc;
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    @JoinTable(name = "genmeta.object_tg_assc", joinColumns = { @JoinColumn(name = "o_id") }, inverseJoinColumns = { @JoinColumn(name = "tg_id") })
    private Set<TemplateGroup> templateGroups;
    @Transient
    private boolean templateGroupsLoaded = false;

    /**
     * Getters and Setters 
     */
}

TemplateGroup.java:

public class TemplateGroup {
    @Id
    @Column(unique=true, nullable=false)
    private int tg_id;
    private String tg_name;
    private String tg_desc;
    @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "templateGroups")
    private Set<Objects> objects;

    /**
     * Getters and Setters 
     */
}

My Problem is, how I could get from my class Object later the data?

Here is my first try: Code Example:

public Set<TemplateGroup> loadTemplateGroups(Objects myObjects) {
    Session session = factory.openSession();
    Set<TemplateGroup> myTG = myObjects.getTemplateGroups();
    session.close();
    return myTG;
}

Thanks a lot.

Best regards Björn

The failed to lazily initialize a collection of role: db.hibernate.classes.Objects.templateGroups, could not initialize proxy - no Session exception is thrown because you are retrieving the Objects instance in one transaction and calling getTemplateGroups() in another(or after the first transaction is committed). You should not open another session to get the template groups.

You need to do something like below:

Session session = factory.openSession();
Objects object = <Code to retrieve the Objects instance>
Set<TemplateGroup> templateGroups = object.getTemplateGroups();
templateGroups.size(); // as an example
session.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM