如何使用注释在休眠中进行一对一映射

时间:2017-04-28 03:44:51

标签: hibernate hibernate-mapping hibernate-criteria hibernate-onetomany

我对hibernate很新。我试图使用注释做一对一(内连接)映射。但我得到了所有被记录的结果 请帮助我从这里来。

我希望得到此查询的结果

select * from employee_1 e join employee_sal es on e.id = es.id;

以下是我的代码和表格结构。

Employee.java

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.OneToOne;
    import javax.persistence.Table;
    @Entity
    @Table(name="employee_1")
    public class Employee {
        @Id
        @Column(name="id")
    private int id;
        @Column(name="name")
    private String name;

   @OneToOne(mappedBy="employee")
    public EmployeeSal employeeSal;
    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;
    }
    @Override
    public String toString(){
        return id+name;
    }

}

EmployeeSal.java

 import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.JoinColumn;
    import javax.persistence.OneToOne;
    import javax.persistence.Table;
    @Entity
    @Table(name="employee_sal")
    public class EmployeeSal {

        @Id
        @Column(name="id")
        private int id;
        @Column(name="sal")
        private int sal;
        @OneToOne
        @JoinColumn(name="id")
        public Employee employee;
        public int getSal() {
            return sal;
        }
        public void setSal(int sal) {
            this.sal = sal;
        }
        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        @Override
        public String toString(){
            return id+sal+"";
        }
    }

Application.java

import org.hibernate.Session;

import hibernate.HibernateUtil;

    public class Application {

        public static void main(String[] args) {

            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            System.out.println(session.createCriteria(Employee.class).list());

        }
    }

HibernateUtil.java

package hibernate;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;


    public class HibernateUtil {
      private static StandardServiceRegistry registry;
      private static SessionFactory sessionFactory;

      public static SessionFactory getSessionFactory() {
        if (sessionFactory == null) {
          try {
            // Create registry
            registry = new StandardServiceRegistryBuilder()
                .configure()
                .build();

            // Create MetadataSources
            MetadataSources sources = new MetadataSources(registry);

            // Create Metadata
            Metadata metadata = sources.getMetadataBuilder().build();

            // Create SessionFactory
            sessionFactory = metadata.getSessionFactoryBuilder().build();

          } catch (Exception e) {
            e.printStackTrace();
            if (registry != null) {
              StandardServiceRegistryBuilder.destroy(registry);
            }
          }
        }
        return sessionFactory;
      }

      public static void shutdown() {
        if (registry != null) {
          StandardServiceRegistryBuilder.destroy(registry);
        }
      }
    }

映射XML

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">


<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">root</property>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test_details</property>
        <property name="format_sql">false</property>
        <property name="show_sql">true</property>
        <property name="hibernate.hbm2ddl.auto" >update</property>


        <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
        <property name="hibernate.c3p0.min_size">7</property>
        <property name="hibernate.c3p0.max_size">53</property>
        <property name="hibernate.c3p0.timeout">100</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">1000</property>
        <property name="hibernate.c3p0.validate">true</property>
        <property name="hibernate.connection.provider_class">org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider</property>

          <mapping class="Employee"/>
          <mapping class="EmployeeSal"/>
     </session-factory>
</hibernate-configuration>

表格结构

employee_1

+------+------+
| id   | name |
+------+------+
|    1 | a    |
|    2 | b    |
+------+------+

employeesal

+------+------+
| id   | sal  |
+------+------+
|    2 |   25 |
+------+------+

1 个答案:

答案 0 :(得分:0)

我给你一些关于一对一关系的示例代码请通过它让我知道如果有些问题.... 我有2张桌子 1.Cart 2.Representative 我的条件是,一个购物车只适用于一位代表.​​..

Cart.java

@OneToOne(fetch=FetchType.EAGER)
    @JoinColumn(name=REPRESENTATIVE_ID)
    private Representative representative;

    public Representative getRepresentative() {
        return representative;
    }

    public void setRepresentative(Representative representative) {
        this.representative = representative;
    }

Representative.java

@OneToOne(mappedBy="representative", cascade=CascadeType.MERGE , fetch=FetchType.EAGER)
    private Carts carts;


    public Carts getCarts() {
        return carts;
    }

    public void setCarts(Carts carts) {
        this.carts = carts;
    }

如果有任何问题,请通过它告诉我。