简体   繁体   English

如何在hibernate中创建Many-One Mapping?

[英]How to create Many-One Mapping in hibernate?

I want to create Many-One Mapping between two tabels, Expense(ID, NAME, CATEGORY) and Category(ID, NAME). 我想在两个表格之间创建多个映射,费用(ID,NAME,CATEGORY)和类别(ID,NAME)。 In my class i have created a field 'Category category' and its setters and getters. 在我的课堂上,我创建了一个字段'Category category'及其setter和getter。 I did them after seeing some stuff from internet. 我从互联网上看到一些东西后做了它们。 What are all the changes i have to do in my Category.java class. 我在Category.java类中需要做的所有更改是什么。 For now, its looks like, 现在,看起来像,

public class Category{
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int catId;
private String catName;

public Category() {
}

public int getCatId() {
    return this.catId;
}

public void setCatId(int catId) {
    this.catId = catId;
}

public String getCatName() {
    return this.catName;
}

public void setCatName(String catName) {
    this.catName = catName;
}

}

I dont want to do mappings with xml config. 我不想用xml配置做映射。 I think, annotations is good for a beginner like me. 我认为,注释对像我这样的初学者来说是好事。

And my Old! 而我的老! SQL query looks like, SQL查询看起来像,

SELECT EXPENSES.EXPNS_ID, EXPENSES.CAT_ID, EXPENSES.NAME, CATEGORY.CAT_NAME FROM EXPENSES INNER JOIN CATEGORY ON EXPENSES.CAT_ID = CATEGORY.CAT_ID WHERE USER_NAME="+currentUserName

How to use inner join in Hibernate? 如何在Hibernate中使用内连接?

Any Suggestions!! 有什么建议么!!

Thanks! 谢谢!


Update 更新

Thanks for all answerers, I tried what you told and it returns a empty list. 感谢所有的回答者,我尝试了你所说的,它返回一个空列表。

To, test i set the 'userName=Tamil' which is in the table. 要测试我设置表中的'userName = Tamil'。 The query generated by Hibernate is looks like below, Hibernate生成的查询如下所示,

select expens0_.expnsId as expnsId1_, expens0_.catId as catId1_, expens0_.category_catId as category7_1_, expens0_.userName as userName1_ from Expens expens0_ inner join Category category1_ on expens0_.category_catId=category1_.catId where expens0_.userName=?

As a beginner, i have some doubts in JPQL, I want catName from Category[catId, catName] table. 作为一个初学者,我在JPQL有些疑惑,我想catNameCategory[catId, catName]表。 And the catId is also available in Expens[expnsId, catId, userName] . catId也可以在Expens[expnsId, catId, userName]

By adding the below lines in Expens.java class, how it will give me catName along with the other variables in the Expens table. 通过在Expens.java类中添加以下行,它将如何为我提供catName以及Expens表中的其他变量。

@ManyToOne
private Category category

// getters, setters

I cant able to understand it. 我无法理解它。 Without understanding this i cant move further, i have to give more mappings in my project. 如果不理解这一点我无法继续前进,我必须在我的项目中提供更多的映射。 If clear with this mapping, i can move to the rest with confidence. 如果使用此映射清除,我可以放心地移动到其余部分。

The query i used is pascal's version: Query query = hSession.createQuery("SELECT e FROM Expens e JOIN e.category c WHERE e.userName = :userName").setParameter("userName", userName); 我使用的查询是pascal的版本: Query query = hSession.createQuery("SELECT e FROM Expens e JOIN e.category c WHERE e.userName = :userName").setParameter("userName", userName);

For me, the query generated by hibernate is looks like same as my Old SQl query. 对我来说,hibernate生成的查询看起来与我的旧SQl查询相同。 I cant able to find problem here. 我在这里找不到问题。

Actually, a big part of the documentation that would be useful in your case is located in the Hibernate Annotations Reference Guides (links provided below). 实际上,在您的案例中有用的文档的很大一部分位于Hibernate Annotations Reference Guides(下面提供的链接)中。 Reading it would be very worth it. 阅读它是非常值得的。

That being said, regarding your specific question, the simplest possible mapping would be: 话虽如此,关于您的具体问题,最简单的映射将是:

@Entity
public class Expense {
    @Id @GeneratedValue
    private Long;

    @ManyToOne
    private Category category

    // getters, setters
    ...
}

That's all. 就这样。

If you want to make it bi-directional, you'll have to add a OneToMany on the other side (and don't forget the mappedBy element since the association is bidirectional): 如果你想使它成为双向的,你必须在另一边添加一个OneToMany (并且不要忘记mappedBy元素,因为关联是双向的):

@Entity
public class Category {
    @Id @GeneratedValue
    private Long id;

    @OneToMany(mappedBy="category")
    private Set<Expense> expenses = new HashSet<Expense>();
    ....
}

And a possible JPQL query would be: 可能的JPQL查询是:

SELECT e FROM Expense e JOIN e.category c WHERE e.username = :username  

Update: Hibernate and JDBC are different. 更新: Hibernate和JDBC是不同的。 With Hibernate, you need to think objects and the above HQL query (which was more an example) will actually return a List<Expense> . 使用Hibernate,您需要考虑对象和上面的HQL查询(这是一个更多示例)实际上将返回List<Expense> To get a category name, iterate over the results and navigate through the association. 要获取类别名称,请迭代结果并浏览关联。 For example: 例如:

List<Expense> expenses = ... // some code to retrieve a list by username

for (Expense expense : expenses) {
    System.out.println(expense.getCategory().getName());
}

References 参考

In your Expense class have: 在您的Expense类中有:

@ManyToOne
@JoinColumn(name="CATEGORY_ID")
private Category category

As pointed in the comments, if you need to access all expenses in a given category, ie have the one-to-many relationship, you can have: 正如评论中所指出的, 如果您需要访问给定类别中的所有费用,即具有一对多关系,您可以:

@OneToMany
private List<Expense> expenses;

I, for example, prefer to use as little @OneToMany mappings as possible - you'd have to manager eager/lazy loading, at some point limiting the number of results, etc. For them I tend to use HQL queries that fetch the subset of objects (expenses in your case) that I need. 例如,我喜欢使用尽可能少的@OneToMany映射 - 你必须管理急切/延迟加载,在某些时候限制结果的数量等。对于他们我倾向于使用获取子集的HQL查询我需要的对象(在你的情况下的费用)。

As Bozho suggested, 正如Bozho所说,

@ManyToOne(fetch=FetchType.EAGER) // Gonna be eager by default anyway
@JoinColumn(name="CATEGORY_ID")
private Category category;

Plus this in your Category class to make it bidirectional, 加上你的Category类中的这个使它成为双向的,

@OneToMany(mappedBy="category")
private List<Expense> expense;

You need not do an inner join like that. 你不需要做那样的内部联接。 When you query the expense, the related category will automatically get loaded eagerly, most likely using join. 查询费用时,相关类别将自动加载,最有可能使用加入。

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

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