2013-08-22 94 views
17

如何在Hibernate中执行此SQL语句?我想用Hibernate来创建查询,而不是创建数据库。HQL Hibernate INNER JOIN

SELECT * FROM Employee e INNER JOIN Team t ON e.Id_team=t.Id_team 

我在SQLServer2008的创建实体类,

@Entity 
@Table(name="EMPLOYEE") 
public class Employee 
{ 
    @Id @GeneratedValue 
    @Column(name="ID_EMPLOYEE") 
    private int id_employee; 
    @Column(name="SURNAME") 
    private String surname; 
    @Column(name="FIRSTNAME") 
    private String firstname; 
    @Column(name="ID_PROFESSION") 
    private int id_profession; 
    @Column(name="ID_BOSS") 
    private int id_boss; 
    @Column(name="HIRED_DATE") 
    private Date hired; 
    @Column(name="SALARY") 
    private double salary; 
    @Column(name="SALARY_ADD") 
    private double salary_add; 
    @Column(name="ID_TEAM") 
    private int id_team; 
//set and get 

@Entity 
@Table(name="TEAM") 
public class Team 
{ 
    @Id @GeneratedValue 
    @Column(name="ID_TEAM") 
    private int id_team; 
    @Column(name="TEAMNAME") 
    private String teamname; 
    @Column(name="ADDRESS") 
    private String address; 
//set and get 

我试图建立在许多方面的工作选择查询,但它仍然无法正常工作。

  SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 
      Session session = sessionFactory.openSession();     
      session.beginTransaction(); 
      String select = "FROM Employee e INNER JOIN Team t ON e.Id_team=t.Id_team"; 
      Query query = session.createQuery(select); 
      List elist = query.list(); 
      session.getTransaction().commit(); 
      session.close();  

也许某事与实体有关?

+0

什么是错误? –

+0

通过您在查询结束时添加t.Id的方式,但是在您的团队实体中,它是id_team。你可以改变它t.id_team –

+0

你错误地创建enity类。我认为你需要重写和使用像多对多,一对一或类似的结构 –

回答

31

连接只能在实体之间存在关联时使用。您的员工实体不应该有一个名为id_team的类型为int的字段映射到列。它应该与团队实体多对一关联映射为JoinColumn:

@ManyToOne 
@JoinColumn(name="ID_TEAM") 
private Team team; 

接着,下面的查询将工作得很好:

select e from Employee e inner join e.team 

这将加载所有的员工,除了那些AREN与任何团队无关。

对于作为实体映射的其他某个表的外键,当然是(id_boss,id_profession)。

现在是您阅读Hibernate文档的时候了,因为您错过了它的一个非常重要的部分以及它是如何工作的。

+0

是否有可能创建一个一对一的关联与员工id_employee和员工id_boss必须删除,因为你在上面写道?这是同一个表(例如:一个工人id_employee = 5的老板id_boss = 1(谁是指id_employee = 1),我应该创建:\t @OneToOne \t @JoinColumn(name = “ID_EMPLOYEE”) \t私人Employee employee; //我希望收到老板的名字,但是这个方法不起作用employeeList.getEmployee()。getSurname(); – szefu

+0

一个老板有很多员工,一个员工有一个老板,所以它应该是'@ManyToOne @JoinColumn(name =“id_boss”)私人雇员老板' –

+0

当然你是对的 – szefu

3
import java.io.Serializable; 
import java.util.ArrayList; 
import java.util.List; 
import javax.persistence.CascadeType; 
import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.OneToMany; 
import javax.persistence.Table; 

@Entity 
@Table(name="empTable") 
public class Employee implements Serializable{ 
private static final long serialVersionUID = 1L; 
private int id; 
private String empName; 

List<Address> addList=new ArrayList<Address>(); 


@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY) 
@Column(name="emp_id") 
public int getId() { 
    return id; 
} 
public void setId(int id) { 
    this.id = id; 
} 
public String getEmpName() { 
    return empName; 
} 
public void setEmpName(String empName) { 
    this.empName = empName; 
} 

@OneToMany(mappedBy="employee",cascade=CascadeType.ALL) 
public List<Address> getAddList() { 
    return addList; 
} 

public void setAddList(List<Address> addList) { 
    this.addList = addList; 
} 
} 

我们有两个实体员工和地址与一对多的关系。

import java.io.Serializable; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.GenerationType; 
import javax.persistence.Id; 
import javax.persistence.JoinColumn; 
import javax.persistence.ManyToOne; 
import javax.persistence.Table; 

@Entity 
@Table(name="address") 
public class Address implements Serializable{ 

private static final long serialVersionUID = 1L; 

private int address_id; 
private String address; 
Employee employee; 

@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY) 
public int getAddress_id() { 
    return address_id; 
} 
public void setAddress_id(int address_id) { 
    this.address_id = address_id; 
} 
public String getAddress() { 
    return address; 
} 
public void setAddress(String address) { 
    this.address = address; 
} 

@ManyToOne 
@JoinColumn(name="emp_id") 
public Employee getEmployee() { 
    return employee; 
} 
public void setEmployee(Employee employee) { 
    this.employee = employee; 
} 
} 

通过这种方式,我们可以实现内部联接两个表

import java.util.List; 
import org.hibernate.Query; 
import org.hibernate.Session; 

public class Main { 

public static void main(String[] args) { 
    saveEmployee(); 

    retrieveEmployee(); 

} 

private static void saveEmployee() { 
    Employee employee=new Employee(); 
    Employee employee1=new Employee(); 
    Employee employee2=new Employee(); 
    Employee employee3=new Employee(); 

    Address address=new Address(); 
    Address address1=new Address(); 
    Address address2=new Address(); 
    Address address3=new Address(); 

    address.setAddress("1485,Sector 42 b"); 
    address1.setAddress("1485,Sector 42 c"); 
    address2.setAddress("1485,Sector 42 d"); 
    address3.setAddress("1485,Sector 42 a"); 

    employee.setEmpName("Varun"); 
    employee1.setEmpName("Krishan"); 
    employee2.setEmpName("Aasif"); 
    employee3.setEmpName("Dut"); 

    address.setEmployee(employee); 
    address1.setEmployee(employee1); 
    address2.setEmployee(employee2); 
    address3.setEmployee(employee3); 

    employee.getAddList().add(address); 
    employee1.getAddList().add(address1); 
    employee2.getAddList().add(address2); 
    employee3.getAddList().add(address3); 

    Session session=HibernateUtil.getSessionFactory().openSession(); 

    session.beginTransaction(); 

    session.save(employee); 
    session.save(employee1); 
    session.save(employee2); 
    session.save(employee3); 
    session.getTransaction().commit(); 
    session.close(); 
} 

private static void retrieveEmployee() { 
    try{ 

    String sqlQuery="select e from Employee e inner join e.addList"; 

    Session session=HibernateUtil.getSessionFactory().openSession(); 

    Query query=session.createQuery(sqlQuery); 

    List<Employee> list=query.list(); 

    list.stream().forEach((p)->{System.out.println(p.getEmpName());});  
    session.close(); 
    }catch(Exception e){ 
     e.printStackTrace(); 
    } 
} 
} 

我已经使用的Java 8 for循环priting名之间。确保你有Tomcat 8的jdk 1.8。为了更好的理解,还要添加一些记录。

public class HibernateUtil { 
private static SessionFactory sessionFactory ; 
static { 
    Configuration configuration = new Configuration(); 

    configuration.addAnnotatedClass(Employee.class); 
    configuration.addAnnotatedClass(Address.class); 
        configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver"); 
    configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");         
    configuration.setProperty("hibernate.connection.username", "root");  
    configuration.setProperty("hibernate.connection.password", "root"); 
    configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect"); 
    configuration.setProperty("hibernate.hbm2ddl.auto", "update"); 
    configuration.setProperty("hibernate.show_sql", "true"); 
    configuration.setProperty(" hibernate.connection.pool_size", "10"); 


    // configuration 
    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); 
    sessionFactory = configuration.buildSessionFactory(builder.build()); 
} 
public static SessionFactory getSessionFactory() { 
    return sessionFactory; 
} 
} 
0

你可以做到这一点,而不必创建一个真正的Hibernate映射。试试这个:

SELECT * FROM Employee e, Team t WHERE e.Id_team=t.Id_team