Hibernate框架中DB表多对多的

来源:互联网 发布:java参考文献近五年的 编辑:程序博客网 时间:2024/06/08 10:34

1.单向:

利用某一方来维护另一方的属性,jdbc中就是外键;

利用get方法和注释方法@ManyToMany;

利用 JUnit4进行单元测试;

比如维护学生和课程表:

package com.geminno.hibernate.entity.unique;


import java.util.Set;


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="HIB_STUDENT")
public class Student {


private int stuid;
private String stuname;

//private Set<Course> courses;


@Id
@GeneratedValue
public int getStuid() {
return stuid;
}


public String getStuname() {
return stuname;
}


/*@ManyToMany
@JoinTable(name="TBL_STU_COURSE",
joinColumns={@JoinColumn(name="STU_ID")},
inverseJoinColumns={@JoinColumn(name="COU_ID")})

public Set<Course> getCourses() {
return courses;
}*/


public void setStuid(int stuid) {
this.stuid = stuid;
}


public void setStuname(String stuname) {
this.stuname = stuname;
}


/*public void setCourses(Set<Course> courses) {
this.courses = courses;
}*/


}



package com.geminno.hibernate.entity.unique;


import java.util.Set;


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


@Entity
@Table(name="HIB_COURSE")
public class Course {


private int cid;
private String cname;
private Set<Student> students;

@Id
@GeneratedValue
public int getCid() {
return cid;
}
public String getCname() {
return cname;
}

@ManyToMany
//@JoinColumn(name="STUDENT_ID")
public Set<Student> getStudents() {
return Students;
}
public void setCid(int cid) {
this.cid = cid;
}
public void setCname(String cname) {
this.cname = cname;
}


public void setStudents(Set<Student> students) {
this.students = students;
}
}


测试:

package testDemo.stu;


import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

public class TestOneMany {

@Test
public void testCreateTable(){

Configuration cfg = new Configuration();
cfg.configure();

SchemaExport se = new SchemaExport(cfg);
se.create(true,true);//打印ddl语句 和输出到数据库

}

}



结果:

九月 20, 2017 3:11:40 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
九月 20, 2017 3:11:40 下午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.8.Final}
九月 20, 2017 3:11:40 下午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
九月 20, 2017 3:11:40 下午 org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
九月 20, 2017 3:11:40 下午 org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
九月 20, 2017 3:11:40 下午 org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
九月 20, 2017 3:11:40 下午 org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
九月 20, 2017 3:11:40 下午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
九月 20, 2017 3:11:40 下午 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
九月 20, 2017 3:11:40 下午 org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator instantiateExplicitConnectionProvider
INFO: HHH000130: Instantiating explicit connection provider: org.hibernate.c3p0.internal.C3P0ConnectionProvider
九月 20, 2017 3:11:40 下午 org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH010002: C3P0 using driver: com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost:3306/mysql0808
九月 20, 2017 3:11:40 下午 org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH000046: Connection properties: {user=root, password=****}
九月 20, 2017 3:11:40 下午 org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH000006: Autocommit mode: false
九月 20, 2017 3:11:40 下午 org.hibernate.c3p0.internal.C3P0ConnectionProvider warnPropertyConflict
WARN: HHH010001: Both hibernate-style property 'hibernate.c3p0.timeout' and c3p0-style property 'c3p0.maxIdleTime' have been set in Hibernate properties.  Hibernate-style property 'hibernate.c3p0.timeout' will be used and c3p0-style property 'c3p0.maxIdleTime' will be ignored!
九月 20, 2017 3:11:40 下午 org.hibernate.c3p0.internal.C3P0ConnectionProvider warnPropertyConflict
WARN: HHH010001: Both hibernate-style property 'hibernate.c3p0.timeout' and c3p0-style property 'hibernate.c3p0.maxIdleTime' have been set in Hibernate properties.  Hibernate-style property 'hibernate.c3p0.timeout' will be used and c3p0-style property 'hibernate.c3p0.maxIdleTime' will be ignored!
九月 20, 2017 3:11:41 下午 com.mchange.v2.log.MLog <clinit>
信息: MLog clients using java 1.4+ standard logging.
九月 20, 2017 3:11:41 下午 com.mchange.v2.c3p0.C3P0Registry banner
信息: Initializing c3p0-0.9.2.1 [built 20-March-2013 10:47:27 +0000; debug? true; trace: 10]
九月 20, 2017 3:11:41 下午 com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource getPoolManager
信息: Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@999e3c14 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@3437bb4a [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, identityToken -> 2zxb229q17vhvdx1xrha22|54a66fe6, idleConnectionTestPeriod -> 0, initialPoolSize -> 5, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 120, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 20, maxStatements -> 100, maxStatementsPerConnection -> 0, minPoolSize -> 5, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@c6cdfb41 [ description -> null, driverClass -> null, factoryClassLocation -> null, identityToken -> 2zxb229q17vhvdx1xrha22|6f1c5be4, jdbcUrl -> jdbc:mysql://localhost:3306/mysql0808, properties -> {user=******, password=******} ], preferredTestQuery -> null, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, factoryClassLocation -> null, identityToken -> 2zxb229q17vhvdx1xrha22|15d80dfe, numHelperThreads -> 3 ]


    alter table HIB_COURSE_HIB_STUDENT 
        drop 
        foreign key FK_j4mgoq6nuog0kw7js5pd51pd1
九月 20, 2017 3:11:42 下午 org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table HIB_COURSE_HIB_STUDENT drop foreign key FK_j4mgoq6nuog0kw7js5pd51pd1
九月 20, 2017 3:11:42 下午 org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: Table 'mysql0808.hib_course_hib_student' doesn't exist


    alter table HIB_COURSE_HIB_STUDENT 
        drop 
        foreign key FK_sfuj85bcqo9crnk8yjr8er088
九月 20, 2017 3:11:42 下午 org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: HHH000389: Unsuccessful: alter table HIB_COURSE_HIB_STUDENT drop foreign key FK_sfuj85bcqo9crnk8yjr8er088
九月 20, 2017 3:11:42 下午 org.hibernate.tool.hbm2ddl.SchemaExport perform
ERROR: Table 'mysql0808.hib_course_hib_student' doesn't exist


    drop table if exists HIB_COURSE


    drop table if exists HIB_COURSE_HIB_STUDENT


    drop table if exists HIB_STUDENT


    create table HIB_COURSE (
        cid integer not null auto_increment,
        cname varchar(255),
        primary key (cid)
    )


    create table HIB_COURSE_HIB_STUDENT (
        HIB_COURSE_cid integer not null,
        students_stuid integer not null,
        primary key (HIB_COURSE_cid, students_stuid)
    )


    create table HIB_STUDENT (
        stuid integer not null auto_increment,
        stuname varchar(255),
        primary key (stuid)
    )


    alter table HIB_COURSE_HIB_STUDENT 
        add constraint FK_j4mgoq6nuog0kw7js5pd51pd1 
        foreign key (students_stuid) 
        references HIB_STUDENT (stuid)


    alter table HIB_COURSE_HIB_STUDENT 
        add constraint FK_sfuj85bcqo9crnk8yjr8er088 
        foreign key (HIB_COURSE_cid) 
        references HIB_COURSE (cid)
九月 20, 2017 3:11:42 下午 org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete

分析:多对多的表关系,hIberbate会自动创建一个表
    create table HIB_COURSE_HIB_STUDENT

默认属性是两张表的主键



2.双向维护

@ManyToMany(mappedBy="students")
public Set<Course> getCourses() {
return courses;
}

利用mappedBy让对方来维护,防止出现两张重复的联合表


自定义表名和列名:

@JoinTable(name="TBL_STU_COURSE",
joinColumns={@JoinColumn(name="COU_ID")},
inverseJoinColumns={@JoinColumn(name="STU_ID")})

原创粉丝点击