zoukankan      html  css  js  c++  java
  • JPA一对一映射案例

    双向和单向的区别,其实不在数据库,而在加载方向。如Student和StudentNo,单向是Student拥有StudentNo的实例可以加载StudentNo,而双向不但Student可以加载StudentNoStudentNo可以拥有Student实例来加载Student。数据库里是两个共享主键的表

    以下模拟双向一对一得映射案例:

    表结构如下:

    Student表结构:


    StudentNo表结构:


    首先需要加入JPA的jar包,别忘了数据库驱动,如图


    建数据库连接配置文件META-INF/persistence.xml

    <?xml version="1.0"?>
    <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd" version="1.0">
       <persistence-unit name="jason" transaction-type="RESOURCE_LOCAL">
          <properties>
             <property name="hibernate.dialect" value="org.hibernate.dialect.OracleDialect"/>
             <property name="hibernate.connection.driver_class" value="oracle.jdbc.driver.OracleDriver"/>
             <property name="hibernate.connection.url" value="jdbc:oracle:thin:@localhost:1521:ORCL"/>
             <property name="hibernate.connection.username" value="jason"/>
             <property name="hibernate.connection.password" value="jason"/>
             
             <property name="hibernate.max_fetch_depth" value="3"/>
             <property name="hibernate.hbm2ddl.auto" value="update"/>
             <property name="hibernate.show_sql" value="false"/>
    	 <property name="hibernate.format_sql" value="false"/>
          </properties>
       </persistence-unit>
    </persistence>

    Student类:

    package com.jason.bean;
    
    import javax.persistence.CascadeType;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.OneToOne;
    
    /**
     * 学员
     * 
     * @author jason
     *
     */
    @Entity
    public class Student {
        
        private Integer id;
        private String name;
        private StudentNo studentNo;
    
        public Student() {
            super();
        }
    
        public Student(String name) {
            super();
            this.name = name;
        }
        @Id
        @GeneratedValue
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
        
        @Column(nullable = false, length = 20)
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
        //optional = true指明StudentNo可为空
        //mappedBy="student"指明Student作为双向关系的维护段,负责外键的更新,起主导作用
        @OneToOne(optional = true, cascade = CascadeType.ALL, mappedBy="student")
        public StudentNo getStudentNo() {
            return studentNo;
        }
    
        public void setStudentNo(StudentNo studentNo) {
            this.studentNo = studentNo;
        }
    }

    StudentNo类:

    package com.jason.bean;
    
    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.OneToOne;
    /**
     * 学员编号
     * 
     * @author jason
     *
     */
    @Entity
    public class StudentNo {
       
        private Integer id;
        private String stuno;
        private Student student;
    
        public StudentNo() {
            super();
        }
        
        public StudentNo(String stuno) {
            super();
            this.stuno = stuno;
        }
        
        @Id
        @GeneratedValue
        public Integer getId() {
            return id;
        }
        
        public void setId(Integer id) {
            this.id = id;
        }
        
        @Column(length = 18,nullable = false)
        public String getStuno() {
            return stuno;
        }
        
        public void setStuno(String stuno) {
            this.stuno = stuno;
        }
        
        //unique= true 指明studentid列的值不可重复
        //optional = false指明Student不可为空
        @OneToOne(cascade = CascadeType.ALL, optional = false)
        @JoinColumn(name = "studentid",referencedColumnName="id", unique = false)
        public Student getStudent() {
            return student;
        }
    
        public void setStudent(Student student) {
            this.student = student;
        }
    
    }

    OneToOneTest测试类:

    package junit.test;
    
    import java.util.List;
    
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.Persistence;
    
    import org.junit.AfterClass;
    import org.junit.BeforeClass;
    import org.junit.Test;
    
    import com.jason.bean.Student;
    import com.jason.bean.StudentNo;
    
    public class OneToOneTest {
    	private static EntityManagerFactory factory;
    	private static EntityManager em;
    	@BeforeClass
    	public static void setUpBeforeClass() throws Exception {
    		 factory = Persistence.createEntityManagerFactory("jason");
    		 em = factory.createEntityManager();
    	     em.getTransaction().begin();
    	}
        /**
         * 添加学员时同时添加对应的学员编号
         */
        @Test
        public void save() {
        	 Student student = new Student();
        	 student.setName("jason");
             StudentNo sn=new StudentNo();
             sn.setStuno("110");
             sn.setStudent(student);
             student.setStudentNo(sn);
    
             em.persist(student);
        }
        
        /**
         * 删除
         */
        @Test
        public void delete() {
            
            //删除学员同时会自动删除学员编号
            em.remove(em.getReference(Student.class, 13));
            
            //删除学员编号同时删除学员
    //        em.remove(em.getReference(StudentNo.class, (Serializable)6));
            
        }
        
        /**
         * 更新
         */
        @SuppressWarnings("unchecked")
        @Test
        public void update() {
            List<Student> students=em.createQuery("select o from Student o").getResultList();
            for(Student sutdent : students){
            	sutdent.setName("张三");
                StudentNo sn=sutdent.getStudentNo();
                if(sn!=null){
                	sn.setStuno("123");
                }
                em.merge(sutdent);
            }
        }
    
        /**
         * 用来判断映射是否成功
         * 
         */
        @Test
        public void test() {
            Persistence.createEntityManagerFactory("jason");
        }
        
        @AfterClass
    	public static void tearDownAfterClass() throws Exception {
        	em.getTransaction().commit();
            em.close();
            factory.close();
    	}
    }

    JUnit运行测试!


  • 相关阅读:
    flock对文件锁定读写操作的问题 简单
    hdu 2899 Strange Fuction(二分)
    hdu 2199 Can you solve this equation? (二分)
    poj 3080 Blue Jeans (KMP)
    poj 2823 Sliding Window (单调队列)
    poj 2001 Shortest Prefixes (trie)
    poj 2503 Babelfish (trie)
    poj 1936 All in All
    hdu 3507 Print Article (DP, Monotone Queue)
    fzu 1894 志愿者选拔 (单调队列)
  • 原文地址:https://www.cnblogs.com/jasontec/p/9601743.html
Copyright © 2011-2022 走看看