zoukankan      html  css  js  c++  java
  • 07-hibernate注解-一对多(多对一)双向外键关联

    一对多(多对一)双向外键

    多方:多方持有一方的引用。

    @ManyToOne(cascade={CasCadeType.ALL},fetch=FetchType.EAGER)

    @JoinColumn(name="cid")

    一方:一方持有多方的集合

    @OneToMany(@cascade={CascadeType.ALL},fetch=FetchType.LAZY)

    @JoinColumn(name="cid")

    第一步:建立学生表:

    1,对应学生类:因为多方持有一方,添加注解:@ManyToOne。

    package otm_bfk;
    import java.util.Date;
    import javax.persistence.CascadeType;
    import javax.persistence.Entity;/*JPA主键*/
    import javax.persistence.FetchType;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.ManyToOne;
    import javax.persistence.Table;
    
    import org.hibernate.annotations.CacheModeType;
    
    /*学生实体类*/
    @Entity
    @Table(name="Students",schema="sys")
    public class Students {
        
        private int sid;
        private String name;
        private String gender;//性别
        private Date birthday;
        private String major;//专业
        
        private ClassRoom classRoom;//多方持有一方的引用
        
        public Students()
        {
            
        }
        
        public Students( String name,String gender, Date birthday, String major) {
            //super();
            this.name=name;
            this.gender = gender;
            this.birthday = birthday;
            this.major = major;
        }
    
        @Id
        @GeneratedValue //主键自动增长
        public int getSid() {
            return sid;
        }
        public void setSid(int sid) {
            this.sid = sid;
        }
        
        @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)
        @JoinColumn(name="cid")
        public ClassRoom getClassRoom() {
            return classRoom;
        }
        public void setClassRoom(ClassRoom classRoom) {
            this.classRoom = classRoom;
        }
    
        public String getGender() {
            return gender;
        }
    
        public void setGender(String gender) {
            this.gender = gender;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public Date getBirthday() {
            return birthday;
        }
    
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
    
        public String getMajor() {
            return major;
        }
    
        public void setMajor(String major) {
            this.major = major;
        }
    }

    第二部:班级类和测试类代码跟前面的一对多单向一样。

    测试结果:

  • 相关阅读:
    Lua 学习之基础篇七<Lua Module,Package介绍>
    Lua 学习之基础篇六<Lua IO 库>
    Lua 学习之基础篇五<Lua OS 库>
    Lua 学习之基础篇四<Lua table(表)>
    Lua 学习之基础篇三<Lua 字符串操作>
    时空穿梭
    【集训队作业】line
    动态几何问题
    博弈论与概率统计
    wombats
  • 原文地址:https://www.cnblogs.com/alsf/p/7828850.html
Copyright © 2011-2022 走看看