[Hibernate] - Annotations - Many To Many

Hibernate annotation 多对多:



下面测试例子会自动生成一张表:card,这张是bank和user表的映射表。里头是bank_id和user_id两个组合字段。

如果想在这张映射表中加入额外的字段,那么hibernate似乎无法做到。因为这需要把多对多写成两个一对多的关系。事实上这样加额外字段到映射表,好像也是违反了DBMS的设计原则。

hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://127.0.0.1/testdb</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

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

        <!-- Enable Hibernate‘s automatic session context management -->
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <mapping class="com.my.bean.User"/>
        <mapping class="com.my.bean.Bank"/>

    </session-factory>

</hibernate-configuration>

HibernateUtil.java

package com.my.dao.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration();
            return configuration.configure().buildSessionFactory(
                    new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build());
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

}

Java Beans:

package com.my.bean;

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

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

@Entity
@Table(name="user")
public class User {
    @Id @GeneratedValue @Column(name="user_id", nullable=false)
    private long userID;

    @Column(name="user_name", length=100, nullable=false)
    private String userName;

    @Column(name="create_time", nullable=false)
    private Date createTime;

    @ManyToMany(cascade=CascadeType.ALL)
    @JoinTable(name="card", joinColumns={@JoinColumn(name="user_id")}, inverseJoinColumns={@JoinColumn(name="bank_id")})
    private Set<Bank> banks = new HashSet<Bank>();

    public long getUserID() {
        return userID;
    }

    public void setUserID(long userID) {
        this.userID = userID;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Set<Bank> getBanks() {
        return banks;
    }

    public void setBanks(Set<Bank> banks) {
        this.banks = banks;
    }
}
package com.my.bean;

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

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;

@Entity
@Table(name="bank")
public class Bank {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="bank_id")
    private long bankID;

    @Column(name="bank_name", length=100, nullable=false)
    private String BankName;

    @ManyToMany(mappedBy="banks", cascade={CascadeType.ALL})
    private Set<User> users = new HashSet<User>();

    public long getBankID() {
        return bankID;
    }

    public void setBankID(long bankID) {
        this.bankID = bankID;
    }

    public String getBankName() {
        return BankName;
    }

    public void setBankName(String bankName) {
        BankName = bankName;
    }

    public Set<User> getUsers() {
        return users;
    }

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

测试:

package com.my.init;
import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.my.bean.Bank;
import com.my.bean.User;
import com.my.dao.util.HibernateUtil;

public class Test {

    public static void main(String[] args) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Transaction tx = session.beginTransaction();

        try {
            //-------------------------------------------------------
            // add user
            //-------------------------------------------------------
            User user = new User();
            user.setUserName("Robin");
            user.setCreateTime(new Date());

            //-------------------------------------------------------
            // add bank
            //-------------------------------------------------------
            Bank bankBCC = new Bank();
            bankBCC.setBankName("BCC");
            Bank bankCBC = new Bank();
            bankCBC.setBankName("CBC");

            //-------------------------------------------------------
            // set relcationship
            //-------------------------------------------------------
            user.getBanks().add(bankBCC);
            user.getBanks().add(bankCBC);

            //-------------------------------------------------------
            // save
            //-------------------------------------------------------
            session.save(user);
            session.save(bankBCC);
            session.save(bankCBC);

            //-------------------------------------------------------
            // remove data
            //-------------------------------------------------------
            session.delete(user);

            tx.commit();
        } catch (Exception e) {
            tx.rollback();
            e.printStackTrace();
        }

        session.close();
    }

}

参考文档:

http://viralpatel.net/blogs/hibernate-many-to-many-annotation-mapping-tutorial/

时间: 09-01

[Hibernate] - Annotations - Many To Many的相关文章

Caused by: java.lang.ClassNotFoundException: org.hibernate.annotations.common.reflection.MetadataPro

1.错误描写叙述 信息: MLog clients using java 1.4+ standard logging. 2014-7-12 19:29:20 com.mchange.v2.c3p0.C3P0Registry banner 信息: Initializing c3p0-0.9.2.1 [built 20-March-2013 10:47:27 +0000; debug? true; trace: 10] 2014-7-12 19:29:21 org.springframework.w

java.lang.ClassNotFoundException: org.hibernate.annotations.common.reflection.MetadataProvider

Caused by: java.lang.NoClassDefFoundError: org/hibernate/annotations/common/reflection/MetadataProvider    at java.lang.Class.getDeclaredConstructors0(Native Method)    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)    at java.lan

Hibernate Annotations

1.HibernateAnnotation依赖包 要使用HibernateAnnotation,您可以从Hibernate站点下载Hibernate3.6和HibernateAnnotation库.除了标准的HibernateJAR和依赖项之外,您还需要如下二个库: 1.HibernateAnnotationjar文件(hibernate-annotations.jar) 2.Java持久性API(lib/ejb3-persistence.jar) 下一步就是获取Hibernate会话工厂.近期

使用Hibernate Annotations

这篇post承接上一篇,用来说明如何使用注解替代映射xml文件.使用注解会很方便,减少了元数据的行数,并且注解是类型安全的.如果注解就是你想从JPA中获得的唯一东西--即用注解取代XML,那么只需要进行如下改动: 主要的变动如下: 1.需要另外导入的包 hibernate/lib/jpa/ hibernate/lib/jpa-metamodel-generator/ 里面的两个jar文件,用来支持注解映射 2.删掉映射xml文件,即Message.hbm.xml文件 3.使用注解映射Messag

Hibernate Annotations 注解

Hibernate Annotations 注解 对于org.hibernate.annotations与org.hibernate.persistence,它的注释比如Columns,可是不知道怎么使用,但是hibernate中也封装了javax.persistence,而且数据库映射注释主要还是使用javax.persistence,即如下注释元素Column,使用规则如下.  分类: Java(66)  [java] view plain copy @Entity 声明当前是一个持久化类

Hibernate 注解 (Annotations 三)多对一双向注解

注解(Annotation),也叫元数据.一种代码级别的说明.它是JDK1.5及以后版本引入的一个特性,与类.接口.枚举是在同一个层次.它可以声明在包.类.字段.方法.局部变量.方法参数等的前面,用来对这些元素进行说明,注释. 接下来我们讲解一下多对一双向注解: 我以部门表和员工表作为示例讲解. 第一步:创建实体类 Dept(部门表) package cn.onetomanydouble.entity; import org.hibernate.annotations.*; import org

Hibernate,JPA注解@SecondaryTable

使用类一级的 @SecondaryTable或@SecondaryTables注解可以实现单个实体到多个表的映射. 使用 @Column或者 @JoinColumn注解中的table参数可指定某个列所属的特定表. 用例代码如下: 数据库DDL语句 1,CAT表 create table CAT ( id VARCHAR2(32 CHAR) not null, create_time TIMESTAMP(6), update_time TIMESTAMP(6), cat_name VARCHAR2

Maven搭建SpringMVC+Hibernate项目详解

前言 今天复习一下SpringMVC+Hibernate的搭建,本来想着将Spring-Security权限控制框架也映入其中的,但是发现内容太多了,Spring-Security的就留在下一篇吧,这篇主要搭建SpringMVC4.1.4和Hibernate4.3.8,之前也打了好多SpringMVC的,这部分已经非常的熟悉了,毕竟业开发过一年多SpringMVC的,这次持久层采用Hibernate,数据源采用c3p0,数据库暂采用MySQL,主要是想复习一下Hibernate.搭建Spring

Hibernate多对一(注解)

1 package cqvie.yjq.Util; 2 3 import java.util.List; 4 5 import org.hibernate.Query; 6 import org.hibernate.Session; 7 import org.hibernate.SessionFactory; 8 import org.hibernate.Transaction; 9 import org.hibernate.cfg.AnnotationConfiguration; 10 11

160727、自定义hibernate主键生成策略生成字符串+数字自增长

需求:需要自增长注解如MyId0001.MyId0002.MyId0003 实现:实现这个接口org.hibernate.id.IdentifierGenerator 一.MyIdGenerator.java(测试用,实际项目中获取链接等可以改变) import java.io.Serializable; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import