我有一个与许多酒吧有关系的foo。
当我删除系统中的bar时,我想将它们保存在数据库中,这是出于某种疯狂的商业原因所以我只是将删除的字段设置为true。
我可以在我的hibernate映射中指定我只希望我的集合保存该字段为false的元素吗?
答案 0 :(得分:3)
您还可以使用SQL语句来保留内容,使用 where 属性:hibernate映射文件的示例位用于设置关系:
<set name="specialConditions" cascade="none" order-by="sortOrder, Text1"
where="Discriminator in ( 'SPECIAL-CURF-AGREEMENT' ) and active = 'Y'"
sort="unsorted" inverse="false" mutable="true" optimistic-lock="true"
embed-xml="true">
<key column="parentID" not-null="false" on-delete="noaction" />
<one-to-many class="au.gov.abs.maserati.domain.entity.Condition" not-found="exception" embed-xml="true" />
</set>
答案 1 :(得分:2)
Hibernate提供filters来完成此任务。
示例bean:
public class Foo {
private Long id;
private String text;
private Set<Bar> bars = new HashSet<Bar>();
// constructors, getters, setters
}
public class Bar {
private Long id;
private boolean deleted;
private String text;
// constructors, getters, setters
}
示例映射 NB:filter
元素
<hibernate-mapping package="org.nkl.hib">
<class name="Foo">
<id name="id" column="FOO_ID">
<generator class="sequence" />
</id>
<property name="text" />
<set name="bars" cascade="all" fetch="join">
<key column="FOO_ID" />
<one-to-many class="Bar" />
<filter name="deleted" condition=":deleted = deleted" />
</set>
</class>
<filter-def name="deleted">
<filter-param name="deleted" type="boolean" />
</filter-def>
</hibernate-mapping>
<hibernate-mapping package="org.nkl.hib">
<class name="Bar">
<id name="id" column="BAR_ID">
<generator class="sequence" />
</id>
<property name="text" />
<property name="deleted" />
</class>
</hibernate-mapping>
单元测试示例:
public class FooBarTest {
private static SessionFactory sessionFactory;
@AfterClass
public static void closeSessionFactory() {
sessionFactory.close();
}
@BeforeClass
public static void setupSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
sessionFactory = configuration.buildSessionFactory();
}
@Test
public void testBarFilter() {
doInTransaction(new Command() {
public void execute(Session session) {
Foo foo = new Foo("foo");
foo.addBar(new Bar("bar1"));
foo.addBar(new Bar("bar2"));
foo.addBar(new Bar("bar3"));
session.save(foo);
}
});
doInTransaction(new Command() {
public void execute(Session session) {
Bar bar = (Bar) session.createQuery(
"from Bar b where b.text = 'bar2'").
uniqueResult();
bar.setDeleted(true);
session.update(bar);
}
});
doInTransaction(new Command() {
public void execute(Session session) {
session.enableFilter("deleted").
setParameter("deleted", Boolean.FALSE);
Foo foo = (Foo) session.createQuery("from Foo").
uniqueResult();
assertEquals(2, foo.getBars().size());
}
});
}
private void doInTransaction(Command command) {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
command.execute(session);
tx.commit();
session.close();
}
}
interface Command {
public void execute(Session session);
}