Многие ко многим

many-to-many

Таблица "posts":

create table posts (
    id integer not null auto_increment,
    content longtext not null,
    primary key (id)
);

Таблица "categories":

create table categories (
    id integer not null auto_increment,
    name longtext not null,
    primary key (id)
);

Таблица "post_category":

create table post_category (
    post_id integer not null,
    category_id integer not null,   
    primary key (post_id, category_id)
);

many-to-many-uml

Файл "Post.java":

package de.inger;

import java.util.Set;

public class Post {

    private Integer id;
    private String content;
    private Set<Category> categories;

    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getId() {
        return id;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getContent() {
        return content;
    }
    public void setCategories(Set<Category> categories) {
        this.categories = categories;
    }
    public Set<Category> getCategories() {
        return categories;
    }
}

Файл "Category.java":

package de.inger;

import java.util.Set;

public class Category {

    private Integer id;
    private String name;
    private Set<Post> posts;

    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getId() {
        return id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName() {
        return name;
    }
    public void setPosts(Set<Post> posts) {
        this.posts = posts;
    }
    public Set<Post> getPosts() {
        return posts;
    }

}

Файл "mapping.hbm.xml":

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="de.inger.Post" table="posts">
        <id name="id" type="integer" column="id">
            <generator class="native" />
        </id>
        <property name="content" type="text" column="content" />
        <set name="categories" table="post_category" cascade="all">
            <key column="post_id" />
            <many-to-many class="de.inger.Category" column="category_id" />
        </set>
    </class>
    <class name="de.inger.Category" table="categories">
        <id name="id" type="integer" column="id">
            <generator class="native" />
        </id>
        <property name="name" type="text" column="name" />
        <set name="posts" table="post_category" cascade="all">
            <key column="category_id" />
            <many-to-many class="de.inger.Post" column="post_id" />
        </set>
    </class>
</hibernate-mapping>

No TrackBacks

TrackBack URL: http://igor-inger.de/mt/mt-tb.cgi/3599

Leave a comment

About this Archive

Find recent content on the main index or look in the archives to find all content.