参考如下
例如:student表和score表需要做联合查询。
1)sql:
select
s.id,s.name,sc.score
from
student
as
s,score
as
sc
where
s.id
=
sc.userId
2)HQL:
select
s.id,s.name,sc.score
from
Student
as
s,Score
as
sc
where
s.id
=
sc.userId
(上面字段都是
javabean的属性)
如果按1)查询的话,必须调用
session.createSQLQuery()方法
如果按2)查询,还是调用
session.createQuery()
如果用xml配置的话,那就写两个配置文件,可以不再用“hibernate.cfg.xml”做文件名,随便什么都可以,像“mysql.cfg.xml”或“sqlserver.xml”都行。用Configuration类获取SessionFactory的代码:SessionFactory mysqlFactory = new Configuration().configure("mysql.cfg.xml").buildSessionFactory()
SessionFactory sqlserverFactory = new Configuration().configure("sqlserver.xml").buildSessionFactory()
如果你用spring,多数据库就更简单了,像这段代码可以完成所有配置:
<beans>
<bean id="mysqlDS" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url">
<value>jdbc:mysql://localhost:3306/test</value>
</property>
<property name="driverClassName">
<value>org.gjt.mm.mysql.Driver</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>123456</value>
</property>
</bean>
<bean id="mysqlFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="mysqlDS"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>test.hbm.xml</value>
</list>
</property>
</bean>
<bean id="sqlserverDS" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="url">
<value>jdbc:odbc:test</value>
</property>
<property name="driverClassName">
<value>sun.jdbc.odbc.JdbcOdbcDriver</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>123456</value>
</property>
</bean>
<bean id="sqlserverFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="sqlserverDS"/>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>test.hbm.xml</value>
</list>
</property>
</bean>
.......
</beans>
hibernate和spring还有很多可行的配置,可以参考他们的references,有很详细地说明的。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)