How to join on two columns using hibernate JPA annotations
2015-09-09 10:30
483 查看
I have the following three relationships
The
The Project:
The Company:
This gives me a
Considering you are using a model like this:
One user has zero or one company;
One user has zero, one or more projects;
The project table holds a foreign key (user_id) to user;
The company table holds a foreign key (user_id) to user.
I think you can define the following JPA mappings:
This way after retrieving a project p you can get the company’s name:
The
Usertable
@OneToMany(mappedBy="user",fetch = FetchType.EAGER,cascade = CascadeType.ALL) @SortNatural SortedSet<Project> projects; @OneToOne(cascade= CascadeType.ALL) Company company;
The Project:
@ManyToOne User user; String company_name;
The Company:
@OneToOne(mappedBy = "company") User user; String name;
This gives me a
user_idin the
Projectstable But I also want the company name , a cloumn from the company table to be in the projects table? How do I join user table and projects table on two columns (
user_idand
company_id) I want the
company_nameto be the name column from the Company table
Considering you are using a model like this:
One user has zero or one company;
One user has zero, one or more projects;
The project table holds a foreign key (user_id) to user;
The company table holds a foreign key (user_id) to user.
I think you can define the following JPA mappings:
//User table @Id Long id; @OneToMany(mappedBy="user",fetch=FetchType.EAGER, cascade=CascadeType.ALL) @SortNatural SortedSet<Project> projects; @OneToOne(mappedBy="user", fetch=FetchType.EAGER, cascade= CascadeType.ALL) Company company; //Project table @Id Long id; @ManyToOne @JoinColumn(name="user_id") User user; //Company table @Id Long id; @OneToOne @JoinColumn(name="user_id") User user; String name;
This way after retrieving a project p you can get the company’s name:
Project p = ... // code to select a project String companyName = p.getUser().getCompany.getName();
相关文章推荐
- Hibernate Oracle sequence的使用技巧
- jsp Hibernate批量更新和批量删除处理代码
- jsp hibernate的分页代码第1/3页
- JAVA+Hibernate 无限级分类
- SSH整合中 hibernate托管给Spring得到SessionFactory
- jsp hibernate 数据保存操作的原理
- hibernate中的增删改查实现代码
- 解决hibernate+mysql写入数据库乱码
- java优化hibernate性能的几点建议
- java Hibernate延迟加载
- hibernate 常用方法介绍
- 深入理解Hibernate中的flush机制
- 解析使用jdbc,hibernate处理clob/blob字段的详解
- 浅析java程序中hibernate的应用总结
- java面试常见问题之Hibernate总结
- 关于Hibernate的一些学习心得总结
- Hibernate管理Session和批量操作分析
- 基于spring+hibernate+JQuery开发之电子相册(附源码下载)
- java Hibernate 一对多自身关联问题
- SpringMVC+MyBatis项目总结(二)