• hibernate多对一双向关联


    多对一单向和一对多单向,在数据库的表现都是在多的一方加上一的外键

    在类里的表现,一对多单向,是在一的一方加上多的引用,多对一单向,是在一的一方加上多的set集合。

    User和Group,一个Group有多个User

    User:

    package com.oracle.hibernate;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    
    @Entity
    public class User {
    
        private int id;
        private String name;
        
        @Id
        @GeneratedValue
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        
    }

    Group:

    package com.oracle.hibernate;
    
    import java.util.HashSet;
    import java.util.Set;
    
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.OneToMany;
    import javax.persistence.OneToOne;
    import javax.persistence.Table;
    
    @Entity
    @Table(name="t_group")//group是mysql的关键字,换个名
    public class Group {
    
        private int id;
        private String name;
        //用set集合,不重复。因为表里的记录也不会重复
        private Set<User>  users = new HashSet<User>();
        
        //一对多
        @OneToMany
        // 指定外键名字,若不指定,hibernate会把一对多当成多对多的一种情况,生成一张临时中间表分别指向user和group     
        @JoinColumn(name="groupId")
        public Set<User> getUsers() {
            return users;
        }
        public void setUsers(Set<User> users) {
            this.users = users;
        }
        @Id
        @GeneratedValue
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        
    }

    生成的表:和一对多单向生成的一样。

    hibernate建表语句:

    create table User (
    id integer not null auto_increment,
    name varchar(255),
    groupId integer,
    primary key (id)
    )

    create table t_group (
    id integer not null auto_increment,
    name varchar(255),
    primary key (id)
    )

    alter table User
    add index FK285FEB744AEC3A (groupId),
    add constraint FK285FEB744AEC3A
    foreign key (groupId)
    references t_group (id)

  • 相关阅读:
    gulp之webpack-stream模块
    AMD、CMD与commonJS
    gulp之gulp-replace模块
    gulp之gulp-uglify模块
    gulp之gulp-sequence模块
    规范-命名、词汇
    gulp之gulp-connect模块
    angularjs $injector:nomod
    because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled
    jxls2 java.lang.NegativeArraySizeException
  • 原文地址:https://www.cnblogs.com/lihaoyang/p/4917145.html
Copyright © 2020-2023  润新知