如何使用JPA通过外键搜索mySql数据库表?

时间:2014-03-18 13:38:49

标签: java mysql jpa eclipselink

我有2个类(BusinessAccount和Projects(如下所示)映射到MySql数据库),其中BusinessAccounts和Projects之间存在1:M关系。我成功地将数据插入数据库,但在查询数据库时遇到了问题。我遇到的问题是我没有外键的getter或setter,在Projects类中没有'contractor_id'。我想要执行的查询是通过在Projects表中搜索外键引用来返回给定BusinessAccount的所有项目的名称列表。我可以在mySQL中做到这一点没有问题,但由于没有引用contractor_id作为Projects类中的java实体,我不知道如何在我的java类中进行搜索。 (注意:我尝试在Projects类中声明外键以及getter和setter,但是因为我已经通过类中的1:Many关系映射了这些,所以它们不会被编译,因为它们被标记为重复实体。)我确信这是显而易见的,我很遗憾,但是非常感谢任何帮助!

public List<Projects> getProjectList() {
    factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    EntityManager em = factory.createEntityManager();   
    List<Projects> projectList = new ArrayList<Projects>();

        em.getTransaction().begin();

        String sessionEmail=Util.getEmail();
        Query myQuery = em.createQuery("SELECT u FROM BusinessAccount u WHERE u.email=:email");
        myQuery.setParameter("email", sessionEmail);

        List<BusinessAccount> userList=myQuery.getResultList();
        BusinessAccount account =userList.get(0);

        Query myQuery2 = em.createQuery("SELECT distinct p.* FROM BusinessAccount u "
                + "INNER JOIN Projects p ON p.contractor_id=:userID");

/*Note p.contractor_id above refers to the entity in the 
mysql database (and won't work obviously), I want to refer 
to it's java equivalent but am not sure how to do that*/

        myQuery2.setParameter("userID", account.getId());
        projectList=myQuery2.getResultList();
        em.getTransaction().commit();
        em.close();

        return projectList;

    } 


@Entity
@Table(name = "business_accounts")
public class BusinessAccount {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "surname")
    private String surname;

        @OneToMany(mappedBy = "businessAccount", fetch = FetchType.EAGER, cascade = { CascadeType.ALL })
    private List<Projects> projects;

    public int getId() {
    return id;
    }

    public void setId(int id) {
    this.id = id;
    }

    public String getFirstName() {
    return firstName;
    }

    public void setFirstName(String firstName) {
    this.firstName = firstName;
    }

    public String getSurname() {
    return surname;
    }

       public List<Projects> getProjects()
    {
    if (projects == null)
    {
        projects = new ArrayList<Projects>();
    }

    return projects;
    }

   public void setProjects(List<Projects> projects)
    {
    this.projects = projects;
    }

    }


@Entity
@Table(name = "projects")
public class Projects {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int project_id;

@Column(name = "project_name")
private String projectName;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumns({ @JoinColumn(name = "contractor_id", referencedColumnName="id") })
private BusinessAccount businessAccount;


public BusinessAccount getBusinessAccount() {
    if (businessAccount == null) {
        businessAccount = new BusinessAccount();
    }
    return businessAccount;
}

public void setBusinessAccount(BusinessAccount businessAccount) {
    this.businessAccount = businessAccount;
}

public int getProject_id() {
    return project_id;
}

public void setProject_id(int project_id) {
    this.project_id = project_id;
}

public String getProjectName() {
    return projectName;
}

public void setProjectName(String projectName) {
    this.projectName = projectName;
}

}

2 个答案:

答案 0 :(得分:3)

JPA查询会像(你需要使用关系属性,但不需要外键本身 - 请尝试,可能需要一些调整):

SELECT p FROM BusinessAccount u, IN(u.projects) p WHERE u.id=:userId

但你真的需要查询吗?您可以从酒店获取相关项目:

BusinessAccount account = ...
List<Projects> projectList = account.getProjects();

答案 1 :(得分:0)

试试这个:

Query myQuery2 = em.createQuery("SELECT distinct p.* FROM BusinessAccount u "
            + "INNER JOIN Projects p ON p.businessAccount=:businessAccount");

myQuery2.setParameter("businessAccount", account);