我试图通过Hibernate插入并选择mysql数据库中的数据,并且Insert对我来说工作正常,但是选择某种方式不要映射正确的表名并且不会返回结果。
获取并插入代码:
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session session = sessFact.getCurrentSession();
session.beginTransaction();
session.save(obj);
session.getTransaction().commit();
try {
Session mysession = HibernateUtil.getSessionFactory().getCurrentSession();
mysession.beginTransaction();
weatherDataObject resultObjectHib = (weatherDataObject) mysession.get(weatherDataObject.class, 26);
mysession.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
sessFact.close();
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="some.pack">
<class name="weatherCoordinates" table="coordinates">
<id name="dataBaseId" column="coordinates_id">
<generator class="native" />
</id>
<property name="lat" type="string" column="coordinates_lat" />
<property name="lon" type="string" column="coordinates_lon" />
</class>
</hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="some.pack">
<class name="weatherDataObject" table="data_object">
<id name="id" column="data_object_id">
<generator class="native" />
</id>
<property name="name" type="string" column="data_object_name" />
<many-to-one name="coord" class="task.main.DataObjects.weatherCoordinates"
column="coordinates_id" unique="true" not-null="true" cascade="all" />
</class>
</hibernate-mapping>
当我看到sql执行字符串时,它是:
Hibernate: insert into coordinates (coordinates_lat, coordinates_lon) values (?, ?)
Hibernate: insert into data_object (data_object_name, coordinates_id) values (?, ?)
Hibernate: select weatherdat0_.data_object_id as data_obj1_1_0_, weatherdat0_.data_object_name as data_obj2_1_0_, weatherdat0_.coordinates_id as coordina3_1_0_ from data_object weatherdat0_ where weatherdat0_.data_object_id=?
问题是weatherdat0
我的表格在某种程度上是错误的,因为我将其映射到文件data_object中的方式不知道如何以及为什么更改任何人可以提供帮助?
答案 0 :(得分:1)
查询是在正确的表上生成的,因为select
查询在表from data_object
上运行
weatherdat0_
只是from
语句中提到的表的别名:
from data_object weatherdat0_
所以它只选择正确的表名。
现在如果查询没有返回任何结果意味着没有匹配id
的记录,所以我建议你直接在数据库上运行查询,看它是否返回任何记录。