public User login(User user){
Session session = sessionFactory.openSession();
String hql="FROM User u WHERE u.userName=:userName AND u.password=:password";
return (User)session.createQuery(hql).setString("userName", user.getUserName())//
.setString("password", user.getPassword()).uniqueResult();
}
测试hibernate与数据库的交互,能不能查询出结果。4.Hibernate与Spring的整合,在applicationContext.xml中创建LocalSessionFactoryBean的bean,ComboPooledDataSource
的bean(这个是c3p0数据库连接池) <context:component-scan base-package=".×" />开启注解开关.
applicationContext.xml中的头文件我列出来:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
4.AOP标签
<tx:advice id="advice" transaction-manager="transactionManager">
<tx:attributes>
<!--REQUIRED:必须的, 有就用没有就创建一个新事务 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<!-- SUPPORTS: 有就有 没有就没有 -->
<tx:method name="*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<aop:config>
<!--
<aop:pointcut expression="execution(* cn.itcast.shop.service.impl.*.*(..))" id="pointcut"/>
-->
<!-- 确定 包.类.方法 切入事务
<aop:advisor advice-ref="advice" pointcut-ref="pointcut"/>
-->
<aop:advisor advice-ref="advice" pointcut="execution(* cn.itcast.service.*.*(..))"/>
</aop:config>
5.Spring和Struts2的整合,在web.xml中加载applicationContext.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
以上仅供参考。