java - 如何在休眠中从一张表中获取实体列表?
问题描述
考虑这个模式
Hospital
----------
id
name
email
phone
Department
----------
id
name
email
phone
Relation
----------
relationId
Hospital_Id
Department_id
这里each
医院有many
科室。所以Hospital
有OneToMany
关系Departments
。Hospital
表有医院列表。Department
表有部门列表。Relation
表加入他们。任何地方都没有使用外键。
现在考虑这些 pojos(为简洁起见,删除了不必要的东西)
public class Hospital {
...
@OneToMany
@JoinColumn(name="Hospital_ID")
private Set<Relation> relations;
...
}
public class Department{
...
@OneToMany
@JoinColumn(name="Department_ID")
private Set<Relation> relations;
...
}
public class Relation{
...
@Id
@Column(name = "relationId")
private int relationId;
@Column(name = "Hospital_ID")
private int hospitalId;
@Column(name = "Department_ID")
private int departmentId;
...
}
所以我的问题是我如何获得任何给定医院的部门列表(或集合)?那就是我想在Hospital
pojo中实现这个方法
public Set<Departments> getDepartments() {
// Return set of departments corresponding to this(object) hospital
}
还有我如何得到相反的结果,即如何在部门类中获得相应的医院对象?
解决方案
你去吧。希望能帮助到你。干杯!
编辑:休眠 cfg 文件位于:
“rootDir\bin\hibernate.cfg.xml”
public class EntityManager
{
// Creates a factory, that creates sessions.
private SessionFactory factory;
/**
* Constructor. Initially connect to the database.
*/
public EntityManager()
{
this.factory = new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory();
}
/**
* Closes the session factory.
*/
public void close()
{
this.factory.close();
}
/**
* Loads the objects of your entity from the database.
*/
public List<YourEntity> loadEntities()
{
Session session = factory.getCurrentSession();
try
{
session.beginTransaction();
@SuppressWarnings("unchecked")
Query<YourEntity> createQuery = session
.createQuery("from YourEntity");
List<YourEntity> result = createQuery.list();
session.getTransaction()
.commit();
return result;
}
finally
{
session.close();
}
}
/**
* Loads entity by id.
*/
public EntityA loadEntity(long entityId)
{
Session session = factory.getCurrentSession();
try
{
session.beginTransaction();
EntityA entity = session.get(EntityA.class, entityId);
return entity;
}
finally
{
session.close();
}
}
/**
* Saves your entity to database.
*/
public void saveEntity(YourEntityA entityA)
{
Session session = factory.getCurrentSession();
try
{
session.beginTransaction();
session.save(entityA);
session.getTransaction()
.commit();
}
finally
{
session.close();
}
}
}
推荐阅读
- javascript - 如何使用变量动态改变对象属性?
- javascript - JavaScript 计算器无法正常工作,不确定我的代码的哪一部分不正确
- docker - 特雷菲克。代理到另一个后端
- python - 如何使用 atom 运行 python 3.X?(视窗)
- java - Android Studio:我如何获得 wrap_content + 价值?
- android - 如何在动画后更改 ImageView 图像
- java - 我可以在宏运行后使用 Java 单击 Excel 的“保存”按钮吗?
- javascript - 如何过滤 react-chartjs-2
- javascript - 有没有最简单的方法来计算重复的一天?
- android - 反应原生动画跳到结束值