我有以下架构:
客户
id - 主键
customer_name
电话 ......
服务
id - 主键
customer_id -- Customer.id 的外键
....................
客户.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="thesis.database.Customer" table="customer">
<meta attribute="class-description">
</meta>
<id name="customerId" type="int" column="customer_id">
<generator class="native" />
</id>
<property name="phone" column="phone" type="string" />
<bag name="services" table="use_service" inverse="false" fetch="join" lazy="false"
cascade="all">
<key column="customer_id" />
<one-to-many class="thesis.database.Service" />
</bag>
</class>
服务.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="thesis.database.Service" table="service">
<meta attribute="class-description">
This class contains the Service detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native" />
</id>
<many-to-one name="customer" class="thesis.database.Customer"
fetch="select">
<column name="customer_id" not-null="true" />
</many-to-one>
....................
</class>
我的功能
public static Customer getCustomerByPhoneNumber(String phoneNumber) {
Session session = getSession();
Criteria criteria = session.createCriteria(Customer.class);
Criterion phone = Restrictions.eq("phone", phoneNumber);
criteria.add(phone);
Customer customer = (Customer) criteria.uniqueResult();
session.close();
return customer;
}
在那之后,我打电话给
Customer customer = getCustomerByPhoneNumber("123456789"); // customer with this phone is availuable in database
我正常得到这个客户,但是我使用 getServices() 函数来获取列表服务,它总是得到相同的列表,尽管我尝试向服务表添加更多记录。
例如:客户表
id customer_name phone ......
1 Mr A 123456789 ......
和服务表
id customer_id 。 ......................
1 1 ......................
2 1 ......................
3 1 ...................... .
先查询。我得到列表大小= 3;在插入一条这样的记录后 4 1 .......... 服务表第二次查询。我也得到了列表大小 = 3;
每个人都可以告诉我为什么并提出任何解决方案吗?预先感谢!
我的解决方案是在添加新记录后使用事务提交。