Hibernate:父子关系数据结构

时间:2014-01-22 22:26:13

标签: java hibernate data-structures parent-child

来源表

文件夹表: -

folder_id,folder_name,parent_id
---------------------------------
1,7-Zip,NULL    
2,7z,1
3,Lang,1

文件表: -

file_id,file_name,folder_id
---------------------------------
1,7-zip.chm,1
2,7-zip.dll,1
3,7z.dll,3
4,af.txt,3

当我插入数据时,数据结构如下(DS的大小为1)

[1,7-Zip, 
childFolders[[2,7z],[3,Lang,childFolders[], childFiles[[3,7z.dll],[4,af.txt]]]],
childfiles[[1,7-zip.chm],[2,7-zip.dll]]]

从数据库中检索数据时,我得到类似的结果。(DS的大小为3)

[1,7-Zip, 
childFolders[[2,7z],[3,Lang,childFolders[], childFiles[[3,7z.dll],[4,af.txt]]]],
childfiles[[1,7-zip.chm],[2,7-zip.dll]]]
[2,7z, 
childFolders[],
childfiles[]]
[3,Lang, 
childFolders[],
childfiles[[3,7z.dll],[4,af.txt]]]
下面是我的文物

SearchedFolder

@Entity
@Table(name="Searchedfolder")
public class SearchedFolder implements Serializable, Comparable<SearchedFolder>{

/**
 * 
 */
private static final long serialVersionUID = -7373115811110399682L;

private long folderId;
private String folderName;
private String path;
private Date searchedTime;
private String description;
private Set<SearchedFile> childFiles = new HashSet<SearchedFile>();
private Set<SearchedFolder> childFolders = new TreeSet<SearchedFolder>();
private SearchedFolder parentFolder;

@Id
@Column(name="folder_id",insertable=true, updatable=true)
@GeneratedValue(strategy = GenerationType.AUTO)
public long getFolderId() {
    return folderId;
}


public void setFolderId(long id) {
    this.folderId = id;
}

@Column(name="path")
public String getPath() {
    return path;
}


public void setPath(String path) {
    this.path = path;
}

@Column(name="searched_time")
public Date getSearchedTime() {
    return searchedTime;
}


public void setSearchedTime(Date searchedTime) {
    this.searchedTime = searchedTime;
}

@Column(name="description")
public String getDescription() {
    return description;
}


public void setDescription(String description) {
    this.description = description;
}

@Column(name="folder_name")
public String getFolderName() {
    return folderName;
}


public void setFolderName(String folderName) {
    this.folderName = folderName;
}

@OneToMany(targetEntity= SearchedFile.class, mappedBy="parentFolder", cascade={CascadeType.ALL}, fetch = FetchType.EAGER)
public Set<SearchedFile> getChildFiles() {
    return childFiles;
}

public void setChildFiles(Set<SearchedFile> childFiles) {
    this.childFiles = childFiles;
}

@OneToMany(mappedBy="parentFolder", cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
public Set<SearchedFolder> getChildFolders() {
    return childFolders;
}


public void setChildFolders(Set<SearchedFolder> folders) {
    this.childFolders = folders;
}

@ManyToOne(cascade={CascadeType.ALL})
@JoinColumn(name="parent_id")
public SearchedFolder getParentFolder() {
    return parentFolder;
}

public void setParentFolder(SearchedFolder parentFolder) {
    this.parentFolder = parentFolder;
}

public int compareTo(SearchedFolder searchedFolder) {

    return this.getFolderName().compareTo(searchedFolder.getFolderName());
}

}

SearchedFile

@Entity
@Table(name="searchedfile" )
public class SearchedFile implements Serializable, Comparable<SearchedFile>{

/**
 * 
 */
private static final long serialVersionUID = -7474936475144364605L;

private long fileId;
private String fileName;
private Date searchedTime;
private String extension;
private String description;
private SearchedFolder parentFolder;

@Id
@Column(name="file_id",insertable=true, updatable=true)
@GeneratedValue(strategy = GenerationType.AUTO)
public long getFileId() {
    return fileId;
}


public void setFileId(long fileId) {
    this.fileId = fileId;
}

@Column(name="file_name")
public String getFileName() {
    return fileName;
}


public void setFileName(String fileName) {
    this.fileName = fileName;
}

@Column(name="searched_time")
public Date getSearchedTime() {
    return searchedTime;
}


public void setSearchedTime(Date searchedTime) {
    this.searchedTime = searchedTime;
}

@Column(name="extension")
public String getExtension() {
    return extension;
}


public void setExtension(String extension) {
    this.extension = extension;
}

@Column(name="description")
public String getDescription() {
    return description;
}


public void setDescription(String description) {
    this.description = description;
}

@ManyToOne(targetEntity= SearchedFolder.class, cascade={CascadeType.ALL}, fetch = FetchType.EAGER)
@NotFound(action = NotFoundAction.IGNORE)
@JoinColumn(name="folder_id")   
public SearchedFolder getParentFolder() {
    return this.parentFolder;
}

public void setParentFolder(SearchedFolder parentFolder) {
    this.parentFolder = parentFolder;
}

public int compareTo(SearchedFile searchedFile) {

    return this.getFileName().compareTo(searchedFile.getFileName());
}


}

DAO文件: -

@Repository
public class SearchedFolderDAOImpl implements SearchedFolderDAO {

@Autowired
private SessionFactory schedulerSessionFactory;

@Override
public void addSearchedData(SearchedFolder searchedFolder) {
    Session session = schedulerSessionFactory.openSession();
    if(session == null){
        schedulerSessionFactory.openSession();
    }
    try{
        session.save(searchedFolder);
      }catch (HibernateException e) {
         e.printStackTrace(); 
      }finally {
          session.close(); 
      }
}

@Override
public List<SearchedFolder> getSearchedData() {
    Criteria ctria = schedulerSessionFactory.getCurrentSession().createCriteria(SearchedFolder.class)
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
            .setFetchMode("childFiles", FetchMode.SELECT);
    List<SearchedFolder> folders = (List<SearchedFolder>) ctria.list();
    return folders;
}

@Override
public void deleteSearchedData(Integer SearchedDataId) {
    // TODO Auto-generated method stub

}

@Override
public List<SearchedFolder> getSearchedData(String folderName) {
    // TODO Auto-generated method stub
    return null;
}

}

服务文件: -

@Service("defaultSearchDataService")
public class SearchDataServiceImpl implements SearchDataService{
{System.out.println("defaultSearchDataService...");}
@Autowired
private SearchedFileDAO searchedFileDAO;
@Autowired
private SearchedFolderDAO searchedFolderDAO;

@Override
@Transactional(readOnly=false, timeout=300, propagation=Propagation.REQUIRES_NEW)
public void saveFiles(List<SearchedFile> files) {
    // TODO Auto-generated method stub

}

@Override
@Transactional(readOnly=true, timeout=300, propagation=Propagation.REQUIRED)
public List<SearchedFile> getFiles() {
    // TODO Auto-generated method stub
    return null;
}

@Override
@Transactional(readOnly=true, timeout=300, propagation=Propagation.REQUIRES_NEW)
public List<SearchedFolder> getFolders() {  
    List<SearchedFolder> folders = searchedFolderDAO.getSearchedData();
    return folders;
}

@Override
@Transactional(readOnly=false,propagation=Propagation.REQUIRES_NEW, timeout=30)
public void addFolder(NewFolderForm newFolderForm) {
    // TODO Auto-generated method stub

}

@Override
@Transactional(readOnly=false, timeout=300, propagation=Propagation.REQUIRED)
public void saveFolder(SearchedFolder searchedFolder) {
    searchedFolderDAO.addSearchedData(searchedFolder);

}

@Override
public void saveFolder(Set<SearchedFolder> directory) {
    Iterator<SearchedFolder> searchedFolderIterator = directory.iterator();
    while(searchedFolderIterator.hasNext()){
        SearchedFolder searchedFolder = searchedFolderIterator.next();
        saveFolder(searchedFolder);
    }
}

}

问题1:为什么插入和检索DataStructures有所不同?

问题2:如何解决此问题

2 个答案:

答案 0 :(得分:0)

您正在插入3个文件夹。插入时:

[1,7-Zip, 
childFolders[[2,7z],[3,Lang,childFolders[], childFiles[[3,7z.dll],[4,af.txt]]]],
childfiles[[1,7-zip.chm],[2,7-zip.dll]]]

您正在同时创建文件夹1,2和3。文件夹2没有文件或子文件夹。但是,文件夹3有3个文件。 当您尝试使用getFolders检索此信息时,您同时检索所有三个文件夹。这就是getSearchedData()所做的。

您可以通过在班级SearchedFolder

中创建新方法来解决此问题
@Override
public List<SearchedFolder> getSearchedFolder(Long folderId) {
    Criteria ctria = schedulerSessionFactory.getCurrentSession().createCriteria(SearchedFolder.class)
            .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
            .setFetchMode("childFiles", FetchMode.SELECT);
    List<SearchedFolder> folders = (List<SearchedFolder>) ctria.list();
    ctria.add(Restrictions.eq("folderId", folderId));
    return folders;
}

答案 1 :(得分:0)

但是想象一下,我们有超过1个根级数据然后可能是解决方案。

e.g.,

1-> 2-> 3 -> 4 -> 5
6-> 7-> 8-> 9
10 -> 11 ->12

现在我们有3个根元素。如何理清这一个?