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

Posted

技术标签:

【中文标题】如何使用注释在休眠中进行一对一映射【英文标题】:How to do one to one mapping in hibernate using annotation 【发布时间】:2017-04-28 03:44:50 【问题描述】:

我对休眠很陌生。我正在尝试使用 annotaion 进行一对一(内部连接)映射。但我得到了所有记录的结果 请帮助我摆脱困境。

我希望得到这个查询的结果

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    |
+------+------+

员工

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

【问题讨论】:

【参考方案1】:

我给你一些一对一关系的示例代码,请仔细阅读,如果有问题,请告诉我.... 我有 2 张桌子 1.购物车 2.代表 我的条件是,一辆购物车只能供一位代表使用......

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;
    

如果有任何问题,请仔细阅读并告诉我。

【讨论】:

感谢您回复我。您的代码还提供了所有记录。即 Hibernate 显示查询打印左外连接 我想执行内部连接。即从具有相同 ID 的两个表中获取记录

以上是关于如何使用注释在休眠中进行一对一映射的主要内容,如果未能解决你的问题,请参考以下文章

休眠一对一映射。从依赖表中删除行

一对多和一对多连续映射的休眠条件查询 - 表或视图不存在

休眠多对一注释外键 javax.el.E​​LException

在一对多映射中使用休眠条件(以行表列作为搜索条件之一的搜索标题表)

如何确保休眠 5 在与共享主键的一对一关系中保持正确的顺序

具有复合键的一对多注释映射