简体   繁体   English

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

[英]How to search mySql database table by foreign key using JPA?

I have 2 classes (BusinessAccount and Projects (shown below) that are mapped to a MySql database) where a 1:M relationship exists between BusinessAccounts and Projects. 我有2个类(BusinessAccount和Projects(如下所示)映射到MySql数据库),其中BusinessAccounts和Projects之间存在1:M关系。 I am successfully inserting data to the database but am having a problem when it comes to querying the database. 我成功地将数据插入数据库,但在查询数据库时遇到了问题。 The problem that I am having is that I have no getter or setter for the foreign key, 'contractor_id' in the Projects class. 我遇到的问题是我没有外键的getter或setter,在Projects类中没有'contractor_id'。 The query that I want to carry out is to return the list of the names of all projects for a given BusinessAccount, by searching by the foreign key reference in the Projects table. 我想要执行的查询是通过在Projects表中搜索外键引用来返回给定BusinessAccount的所有项目的名称列表。 I can do this no problem in mySQL but as there is no reference to the contractor_id as a java entity in the Projects class, I'm not sure how to do this search from within my java class. 我可以在mySQL中做到这一点没有问题,但由于没有引用contractor_id作为Projects类中的java实体,我不知道如何在我的java类中进行搜索。 (Note: I tried to declare the foreign key along with getters and setters in the Projects class but as I have these mapped by the 1:Many relationship in the class already, it wouldn't compile as they were flagged as duplicate entities.) I'm sure it's something obvious that I'm missing but any help is much appreciated! (注意:我尝试在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;
}

}

The JPA query would be something like (you need to use the relation property, but no need for the foreign key itself - please try, it may need some tweaking): JPA查询就像(你需要使用关系属性,但不需要外键本身 - 请尝试,它可能需要一些调整):

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

But do you really need the query? 但你真的需要查询吗? You can get the related projects from the property: 您可以从酒店获取相关项目:

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

Try this: 尝试这个:

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

myQuery2.setParameter("businessAccount", account);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM